[英]Java - Writing to a text file [on hold]
我目前有一个 stream 编写器,它从文本文件中读取type
、 firstName
、 state
、 address
、 suburb
、 points
和lastName
等对象,并将它们显示在 Z78E6221F6393D1356DZF84CE963 中
我将如何使用这些对象将 go 写入文本文件?
这是我目前在阅读文本文件时所拥有的
Scanner scnr = new Scanner(System.in);
Driver[] drivers = new Driver[100];
int i = 0, j = 0;
try {
Scanner scan = new Scanner(new File("driver.txt"));
while (scan.hasNextLine()) {
String line = scan.nextLine();
String data[] = line.split(",");
String number = data[0];
String type = data[1];
String firstName = data[2];
String lastName = data[3];
String address = data[4];
String suburb = data[5];
double points = Double.parseDouble(data[6]);
String state = data[8];
drivers[i] = new Driver(number, type, firstName, lastName, address, suburb,
points, state);
i++; j++;
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found!");
}
您需要ObjectOutputStream
将对象写入文件。 Please check https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html for API doc. 您可以在 Internet 上找到有关ObjectOutputStream
的几个示例,例如http://tutorials.jenkov.com/java-io/objectoutputstream.html
作为提示,您只需要一个类似于以下的代码:
//Assuming class Driver implements Serializable
FileOutputStream fos = new FileOutputStream("drivers.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(drivers);
oos.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.