1.二进制文件读写示例,复制一个文件内容到另一个文件:
//对二进制文件,将src文件内容复制到另外一个文件des中
public void copyFile(String src, String des){
try (FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(des)) {
//定义一个数组 用于保存 一次性读取的多个字节
byte[] buffer = new byte[1024];
//从输入流里面按字节顺序读出,写入到输出流
while((fis.read(buffer)) != -1) {//read()返回-1时,说明内容已经读完
fos.write(buffer);//write() 按字节顺序写入
}
fos.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2.字符流文本文件读写示例
//读取字符流文件
public void readTxtFile(String srcPath){
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(srcPath)));
String line = null;
while((line = reader.readLine()) != null){
// TODO: 2021/10/9 业务逻辑
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//向字符流文件中写入数据
public void writeTxtFile(String desPath, String content){
PrintWriter writer = null;
try {
writer = new PrintWriter(new FileOutputStream(desPath));
writer.println(content);//输出一行
writer.flush();//刷新缓存,确保内容被输出到文件中
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
参考剪藏:
java知识积累---数据流_逸风如梦_新浪博客 //这一篇详细列举了各种java数据流
Java的输入输出与文件处理 - 简书