我的程序中有某些数组列表,我想将其写入文件中,以便在第二次启动程序时可以读取它们。 目前它适用于人员数组列表。
阅读部分:
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("test.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
team.setPersonList((ArrayList<Person>) ois.readObject());
writeToFile 类:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class WriteToFile {
public void write(ArrayList<Person> Data ) throws IOException, ClassNotFoundException{
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(Data);
// close the stream
oout.close();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("test.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// read and print what we wrote before
System.out.println("" + ois.readObject());
ois.close();
}
}
主要内容:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, IOException{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
Team team = new Team(scan);
new InlogSystem(team, scan);
ArrayList<Person> playersData = team.getPersonList();
WriteToFile x = new WriteToFile();
x.write(playersData);
scan.close();
}
}
这就是工作部分, 现在我想要使用相同的 writeToFile 类将字符串数组列表写入另一个 txt 文件(不像 personlist 那样进行测试)。 显然 write 方法只适用于 person 类型的数组列表,并且它总是将数组保存到“test.txt”中。
如何在不创建新方法且不包含大量模糊代码的情况下编写此数组列表? 非常感谢!
最佳答案
您可以更改参数类型ArrayList<String>
至ArrayList<?>
甚至 List<?>
或者,我建议,Object
。然后,您的方法就能够编写任意对象。
使用泛型在这里是没有用的:它提供编译时类型检查,这不会在您的方法中使用。
顺便说一下,你的异常处理非常糟糕。我建议你捕获并重新抛出 ClassNotFoundException
作为IOException
; FileNotFoundException
只是 IOException
的子类并且不需要单独捕获 - 为什么你会捕获 IOException
当你的方法被声明为 throws IOException
时根本没有?
关于java - 在java中使用相同的writeToFile写入不同的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17264923/