0

I have a csv file containing a list under following : (Title,artist,highest position). I am trying to write to new file where position is 1.

When I run the following code the new file generates but it is empty: Any ideas? thanks!

File newFile = new File("newsonglist.csv");
    File orignal = new File("songlist.csv");
    
    String line;
            
    try {
        
        FileReader fr = new FileReader(orignal.getName());
        BufferedReader br = new BufferedReader(fr);
        br.readLine();
        
        FileWriter fw = new FileWriter(newFile.getName());
        BufferedWriter bw = new BufferedWriter(fw);
        
        line = br.readLine();
        
        while(line!=null) {
            System.out.println(line);
            if(line.contains("1")) {
                bw.write(line);
            }
            
            line = br.readLine();
        }
        
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
culldog88
  • 83
  • 7
  • You need to flush and close the `BufferedWriter`. Does this answer your question? [Bufferedwriter works, but file empty?](https://stackoverflow.com/questions/18573998/bufferedwriter-works-but-file-empty) – sorifiend Mar 17 '21 at 23:04
  • 1
    Also what is the purpose of newFile and original if you pass the Reader/Writer only the name of them? Either remove those File properties or pass the FileReader and FileWriter the file itself (```new FileReader(orignal)```, etc.) – Catalin Pirvu Mar 17 '21 at 23:15
  • Also (1) you are losing all the line terminators: you need to call `BufferedWriter.newLine()` after every `write()`; and (2) you aren't closing any of the files. – user207421 Mar 18 '21 at 00:27

0 Answers0