-
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) {
}
}
}
-
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.
-
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
Forum Rules
|
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
|
Bookmarks