-2

This is very stupid to ask but I want to know. I have to read a line of text and write in seperate file. I know how to read a line and work on that text but I don't know putting both together. I have a text file with data in it, has header on the top, and I need header on every new file with data from next line on new file. I am able to create logic for that. Please help me.

Pawriwes
  • 283
  • 1
  • 6
  • 21

1 Answers1

1

Lots of examples on web

PrintWriter writer = null;
try {
    writer = new PrintWriter(new FileWriter(new File("pathToNewFile")));

    //do reading etc
    writer.println(stringVariableToWrite);

} catch (IOException e) {
    System.err.println(e);
} finally {
    if (writer != null){
        writer.close();
        if (writer.checkError()) {
             System.err.println(e);
        }
    }
}
Matt3o12
  • 4,192
  • 6
  • 32
  • 47
tomgeraghty3
  • 1,234
  • 6
  • 10
  • The writer might be `null`. I think, you should add an if statemant to check it (`if (writer != null) writer.close()`). – Matt3o12 Apr 25 '13 at 15:17
  • @Matt3o12 you are spot on! the if (writer != null) line needs adding. – tomgeraghty3 Apr 25 '13 at 15:18
  • Thank you, but, I am confused here, like I have to store the header and read all other after the header and put both the text(i.e header and other line) – Pawriwes Apr 25 '13 at 15:33
  • Why can't you just read in line by line and write each new line as you read it. This would also include reading in the header first before the other lines. (I assume by "header" you just mean the first line in the file?) – tomgeraghty3 Apr 25 '13 at 15:42