【发布时间】:2018-04-14 06:20:30
【问题描述】:
如何读取文本文件中的多个对象。我正在尝试阅读文本文件。我总是只得到文件的第一个对象。如何从文本文件中获取所有对象...
List<Processedfile> processfiles = new ArrayList<Processedfile>();
Processedfile processfile = new Processedfile();
processfile.setFilename(filename);
processfile.setCountrow(uploadedFileCount);
processfile.setDate(dateformat);
processfiles.add(processfile);
writeReportTextFile(processfiles);
将处理后的文件对象写入文本文件...
写入文件
public void writeReportTextFile(List<Processedfile> processfiles) {
String processedfilereport = "D:\\PaymentGatewayFiles\\MSSConsolidate\\processedfilereport.txt";
try {
File file = new File(processedfilereport);
FileOutputStream f = new FileOutputStream(file.getAbsoluteFile(), true);
// System.out.println(file);
ObjectOutputStream s = new ObjectOutputStream(f);
// System.out.println("the write"+reportfile);
s.writeObject(processfiles);
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
读取文件..
public List<Processedfile> processreportfileread() {
List<Processedfile> a1 = new ArrayList();
String processedfilereport = "D:\\PaymentGatewayFiles\\MSSConsolidate\\processedfilereport.txt";
try {
File file = new File(processedfilereport);
FileInputStream r = new FileInputStream(file);
ObjectInputStream sp = new ObjectInputStream(r);
a1 = (List) sp.readObject();
System.out.println("the list is" +a1);
Iterator i = a1.iterator();
while(i.hasNext()) {
System.out.println("the iterator report is ===="+i.next());
}
}
catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return a1;
}
【问题讨论】:
-
请添加一些代码。向我们展示您尝试使用上面订阅的内容实现的代码,并标记您遇到的问题。
-
问得好,除非您发布您正在使用的代码并提供文本文件包含的示例,否则我们很可能永远无法告诉您为什么会遇到此问题。跨度>
-
1.您正在编写/阅读的不是文本文件。它包含对象列表的二进制序列化表示。 2. 你只是将一个 Processedfile 添加到你正在写入文件的列表中。那么为什么在读回它时会期望多个对象呢? 3. 不要使用原始类型。使用 List
和 Iterator 而不是 List 和 Iterator。 -
每次我写文件名和countrow..另一个文件来然后在同一个文本文件中添加文件名和countrow..所以我想将文本文件信息显示到前端。
-
回答这个问题:您只是将一个 Processedfile 添加到您正在写入文件的列表中。那么,为什么在回读时会期望多个对象呢?