DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 3 of 3
  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.

Bookmarks

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


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links