package com.java;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOTest2 {
/**
* 字节流操作文件读写
*/
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("from.txt");
fos = new FileOutputStream("to.txt");
// 单个字符的循环输入输出
oneWordIO(fis, fos);
// 一行一行循环输入输出
oneLineIO(fis, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 一行一行循环输入输出
*/
private static void oneLineIO(FileInputStream in, FileOutputStream out)
throws IOException {
byte[] buf = new byte[1024];
int len = -1;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
out.flush();
}
}
/**
* 单个字符的输入输出
*/
private static void oneWordIO(FileInputStream in, FileOutputStream out)
throws IOException {
int ch = -1;
while ((ch = in.read()) != -1) {
out.write(ch);
out.flush();
}
}
}
java IO总结之字节流操作文件读写
这篇博客详细介绍了如何使用Java的FileInputStream和FileOutputStream进行字节流操作,包括单个字符和整行的文件读写。通过示例代码展示了如何打开文件、进行数据传输并确保文件正确关闭。
摘要由CSDN通过智能技术生成