Skip to content
Advertisement

How to save Each index of Array List in text file as new line in java?

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

Save Formate

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();
    }
    

Advertisement

Answer

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.

    public void ReadFromText() {
        // Read from Text file and save in both lists
        List<Integer> output1 = new ArrayList<>();
        List<Integer> output2 = new ArrayList<>();
        try {
            Path path = Path.of("D:\Sample.txt");
            List<String> inputList = Files.lines(path).collect(Collectors.toList());
            for (int i = 0; i < inputList.size(); i++) {
                String s = inputList.get(i);
                if (!s.isEmpty()) {
                    if (i < First.size()) {
                        output1.add(Integer.valueOf(s));
                    } else {
                        output2.add(Integer.valueOf(s));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement