'How to Add header row in text file using java

I have requirement to add header row in existing text file, is there any way to do it without affecting any other file format or structure.



Solution 1:[1]

Read the file, add the header and save the file:

try{
    BufferedReader in = new BufferedReader(new FileReader(yourFile));
    String header = "Your Header";
    String content = "";
    while (in.ready()) {
      content += in.readLine();
    }
    in.close();

    String output = header + System.getProperty("line.separator") + content;

    FileWriter fstream = new FileWriter(YourOutputFile);
    BufferedWriter out = new BufferedWriter(fstream);
    out.write(output);  
    out.close();

  }catch (IOException e){
    System.err.println("Error: " + e.getMessage());
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gary