Reading to end of text file and insert text on the next line


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Reading to end of text file and insert text on the next line

  1. #1
    Join Date
    Feb 2005
    Location
    USA
    Posts
    3

    Smile Reading to end of text file and insert text on the next line

    Hello out there...

    Below is a simple code that appends a string at the end of a file. My question is how do you append a string on the next line. For example, let's say my test.txt file had:
    ////////////////
    Hello
    World
    Java

    ///////////////
    Assume I want to append "JELLO". The source code below will append JELLO right after Java: JavaJELLO.
    What I want is to have:
    Java
    JELLO

    Thanks guys.

    import java.io.*;
    class TextWriter {

    public static void main(String[] args) {
    String textToAppend = "JELLO";
    File file = new File("test.txt");
    try {
    Writer writer = new BufferedWriter(new FileWriter(file, true));
    writer.write(textToAppend, 0, textToAppend.length());
    writer.close();
    } catch (IOException e) {
    }
    }
    }

  2. #2
    Join Date
    Dec 2004
    Posts
    34
    Just change the Writer to BufferedWriter and use a newLine() before the append:

    import java.io.*;
    class TextWriter {
    public static void main(String[] args) {
    String textToAppend = "JELLO";
    File file = new File("test.txt");
    try {
    BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
    writer.newLine();
    writer.write(textToAppend, 0, textToAppend.length());
    writer.close();
    } catch (IOException e) {
    }
    }
    }



    Beware though, if the file is empty it'll put a blank line in the beginning. The workaround is to check if the file exists, but I think it's best to keep it simple.

  3. #3
    Join Date
    May 2004
    Posts
    219
    Or, you know, use a newline character (\n) first

    edit: They've really bloated up this site. I can't even load the forums with Opera anymore.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center