0

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.

UmeshR
  • 803
  • 1
  • 9
  • 16

1 Answers1

0

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());
  }
Gary
  • 13,303
  • 18
  • 49
  • 71
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
  • I am using talend Open studio to automate some files using Dynamic schema load and it has constraint to each files must have header row. – UmeshR Mar 22 '13 at 06:20
  • i can not do replication of files to just add header row because i have files which big in size some of them are more than 50GB – UmeshR Mar 22 '13 at 06:25
  • You can write output to the same file, you can delete the old file if you want, but you should consider having a copy for any case which you optionally delete after checking that it works as you expect. – CloudyMarble Mar 22 '13 at 06:34
  • that solution I have with me, I just wanted to reduce time frame which we have to spend on recreate the file. – UmeshR Mar 22 '13 at 06:48
  • 1
    Thats exactly why you should have mentioned all this relelvant info in your question. – CloudyMarble Mar 22 '13 at 06:59
  • Any way there is no way to avoid reading and writing the file, not in java at least – CloudyMarble Mar 22 '13 at 07:00