Brandon
Brandon

Reputation:

Converting .txt files into one .csv. Exported information overwrite the first line. Any Tips?

I have been working on a project to read data off of multiple .txt file to convert it to a .csv file. My issues is that the exported data keeps overwriting the first line so everytime i export the file it only shows the last line. Does anyone have any tips to help me out?

//Reading the information from the files.
for (String fileName : textFileNames) {
  try (Scanner sc = new Scanner(new File(stack + "\\" + fileName));) {
    fileIn = sc.nextLine();

    while (fileIn != null) {
      String line = fileIn;
      String[] split = line.split("\\s+");
      StringJoiner joiner = new StringJoiner(",");

      for (String strVal : split) {
        joiner.add(strVal);
      }

      line = joiner.toString();
      line = line.startsWith(",") ? line.substring(1) : line;
      System.out.println(line);

      BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv"));
      StringBuilder sb = new StringBuilder();

      // Append strings from array
      sb.append(line);
      sb.append("\n");


      br.write(sb.toString());
      br.close(); 

      fileIn = sc.nextLine();
    } 


    sc.close();

  } catch (IOException ex) {
    Logger.getLogger(Class_Organizer_Krause.class.getName())
          .log(Level.SEVERE, null, ex);
  }

}

Upvotes: 0

Views: 18

Answers (2)

Olivier Boissé
Olivier Boissé

Reputation: 18153

BufferedWriter br = new BufferedWriter(new FileWriter("myfile.csv", true)); should solve your problem.

Here is the documentation

By the way you should move these Resources creations inside the try https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html to avoid having unclosed resources if an exception occurs

try (Scanner sc = new Scanner(new File(stack + "\\" + fileName));
     FileWriter fw = new FileWriter("myfile.csv", true);
     BufferedWriter br = new BufferedWriter(fw);
) {
 ...
 // you can remove br.close(); 
}

Upvotes: 1

R-D
R-D

Reputation: 1154

You are recreating the BufferedWriter within the while loop, essentially re-creating the file every time you loop to a new line in your input file.

Move the construction of the BufferedWriter out of the while loop (right before it), move the close statement to right after the while loop and it should be fine.

Upvotes: 1

Related Questions