我是一个新手,我真的很想学习这个概念,而不仅仅是复制和粘贴代码。我想了解如何准确地使用 Jave IO,但看到我的不同版本的代码感到困惑和失望。
所以我自己做了笔记,想和这里的专家确认一下我是否做对了。这些仅供我自己参考。我知道这并不完美,但如果您能确认它们是否正确,我将不胜感激。
使用 BufferedWriter 和 FileWriter 写入文本文件(作为字符)。缺点是您不能编写原始数据类型。
前任:
BufferedWriter bw= new BufferedWriter (new FileWriter("a.txt", true));
String x;
while ((x=bw.readLine())!=null){
bw.newLine();
bw.write(x);
bw.flush();}
使用 BufferedReader 和 FileReader 读取文本文件(作为字符)
前任:
BufferedReader br = new BufferedReader (new FileReader("b.txt"));
String x;
while ((x=br.readLine())!=null){
System.out.println(x);}
使用 DataOutputStream 和 FileOutputStream 写入文本文件(二进制)。优点是您可以编写原始数据类型以及字符串。
前任:
DataOutputStream dos = new DataOutputStream(new FileOutputStream("out.txt"));
dos.writeInt(cityIdA); // int cityIdA = 9897;
dos.writeUTF(cityNameA); // String cityNameA = "Green Lake City";
dos.writeInt(cityPopulationA); // int cityPopulationA = 500000;
dos.writeFloat(cityTempA); // float cityTempA = 15.50f;
dos.flush();
使用 DataInputStream 和 FileInputStream 读取文本文件(二进制)。优点是您可以读取原始数据类型以及字符串。
前任:
DataInputStream dis = new DataInputStream(new FileInputStream("inp.txt"));
int cityId1 =dis.readInt(); // int cityIdA = 9897;
String cityName1 =dis.readUTF(); // String cityNameA = "Green Lake City";
int cityPopulation1 =dis.readInt(); // int cityPopulationA = 500000;
float cityTemperature1 =dis.readFloat(); // float cityTempA = 15.50f;
实际代码:
import java.io.*;
class b{
public static void main (String args[]) throws IOException{
int cityIdA = 9897;
String cityNameA = "Green Lake City";
int cityPopulationA = 500000;
float cityTempA = 15.50f;
BufferedWriter bw = new BufferedWriter(new FileWriter("shahar.txt"));
bw.write("9897");
bw.write("Green Lake City");
bw.write("500000");
bw.write("15.50");
bw.flush();
bw.close();
DataOutputStream dos = new DataOutputStream(new FileOutputStream("out.txt"));
dos.writeInt(cityIdA);
dos.writeUTF(cityNameA);
dos.writeInt(cityPopulationA);
dos.writeFloat(cityTempA);
dos.flush();
BufferedReader br = new BufferedReader (new FileReader("shahar.txt"));
String x;
while ((x=br.readLine())!=null){
System.out.println(x);}
DataInputStream dos1 = new DataInputStream(new FileInputStream("out.txt"));
int cityId1 = dos1.readInt(); // int cityIdA = 9897;
System.out.println( cityId1);
String cityName1 =dos1.readUTF(); // String cityNameA = "Green Lake City";
System.out.println(cityName1);
int cityPopulation1 =dos1.readInt(); // int cityPopulationA = 500000;
System.out.println(cityPopulation1);
float cityTemperature1 =dos1.readFloat(); // float cityTempA = 15.50f;
System.out.println(cityTemperature1);
}
}