如何将文本文件中数组列表的每个索引保存为java中的新行?
我试图以下面的Java格式将列表的每个索引作为新行中的新行保存为新行,并读取与以后的两个单独的数组列表相同。我已经完成了保存部分,现在我想将其重新读回两个单独的列表
public class SaveLists{
private List<Integer> First= new ArrayList<>();
private List<Integer> second= new ArrayList<>();
public void save(List l) throws IOException{
try{
File f = new File ("E:\\Sample.txt");
if (!f.exists()) {
f.createNewFile();
}
FileWriter fw = new FileWriter(f.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
for(Object s : l) {
bw.write(s + System.getProperty("line.separator"));
}
bw.write(System.getProperty("line.separator"));
bw.close();
}catch(FileNotFoundException e){System.out.println("error");}
}
public void ReadFromText(){
//Read from Text file and save in both lists
}
}
班级主要:
public static void main(String[] args) {
temp t = new temp();
t.First.add(1);
t.First.add(2);
t.First.add(3);
t.second.add(6);
t.second.add(5);
t.second.add(4);
t.save(t.First);
t.save(t.second);
// t.ReadFromText();
}
I am trying to save each index of list as new line in text file in format below in java and read same as two separate Array List for later . I have done the saving part now i want to read it back into two separate lists
Class SaveLists
public class SaveLists{
private List<Integer> First= new ArrayList<>();
private List<Integer> second= new ArrayList<>();
public void save(List l) throws IOException{
try{
File f = new File ("E:\\Sample.txt");
if (!f.exists()) {
f.createNewFile();
}
FileWriter fw = new FileWriter(f.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
for(Object s : l) {
bw.write(s + System.getProperty("line.separator"));
}
bw.write(System.getProperty("line.separator"));
bw.close();
}catch(FileNotFoundException e){System.out.println("error");}
}
public void ReadFromText(){
//Read from Text file and save in both lists
}
}
Class Main :
public static void main(String[] args) {
temp t = new temp();
t.First.add(1);
t.First.add(2);
t.First.add(3);
t.second.add(6);
t.second.add(5);
t.second.add(4);
t.save(t.First);
t.save(t.second);
// t.ReadFromText();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于两个保存操作都在同一线程上,因此这些行将以同步方式写入文件。因此,从文件中读取所有行后,我们可以根据输入列表的大小拆分行,即第一组值将由“First”列表插入。
As both the save operations are on the same thread the lines would be written to the file in a synchronous manner. So after reading all the lines from the file we can split the lines based on the size of the input lists i.e. the first set of values would have been inserted by the 'First' list.