FileInputStream 和 FileOutputStream:
FileInputStream fis = new FileInputStream("input.txt");
int data;
while ((data = fis.read()) != -1) {
// 处理字节数据
}
fis.close();
FileOutputStream fos = new FileOutputStream("output.txt");
fos.write(byteArray);
fos.close();
BufferedInputStream 和 BufferedOutputStream:
flush()
方法来强制刷新。 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"));
int data;
while ((data = bis.read()) != -1) {
// 处理字节数据
}
bis.close();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"));
bos.write(byteArray);
bos.close();
FileReader 和 FileWriter:
FileReader reader = new FileReader("input.txt");
int data;
while ((data = reader.read()) != -1) {
// 处理字符数据
}
reader.close();
FileWriter writer = new FileWriter("output.txt");
writer.write(charArray);
writer.close();
BufferedReader 和 BufferedWriter:
flush()
方法来强制刷新。 BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = br.readLine()) != null) {
// 处理一行字符数据
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write("Hello, World!");
bw.close();
DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"));
int intValue = dis.readInt();
double doubleValue = dis.readDouble();
dis.close();
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"));
dos.writeInt(42);
dos.writeDouble(3.14);
dos.close();
Serializable
接口。不适用于与其他非Java系统交互。 DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"));
int intValue = dis.readInt();
double doubleValue = dis.readDouble();
dis.close();
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"));
dos.writeInt(42);
dos.writeDouble(3.14);
dos.close();
好处:
坏处:
Serializable
接口。