PrintWriter append method not appending
The fact that PrintWriter
's method is called append()
doesn't mean that it changes mode of the file being opened.
You need to open file in append mode as well:
PrintWriter pw = new PrintWriter(new FileOutputStream(
new File("persons.txt"),
true /* append = true */));
Also note that file will be written in system default encoding. It's not always desired and may cause interoperability problems, you may want to specify file encoding explicitly.
PrintWriter to append data if file exist
Once you call PrintWriter out = new PrintWriter(savestr);
the file is created if doesn't exist hence first check for file existence then initialize it.
As mentioned in it's Constructor Docmentation as well that says:
If the file exists then it will be truncated to zero size; otherwise, a new file will be created.
Since file is created before calling f.exists()
hence it will return true
always and ìf
block is never executed at all.
Sample code:
String savestr = "mysave.sav";
File f = new File(savestr);
PrintWriter out = null;
if ( f.exists() && !f.isDirectory() ) {
out = new PrintWriter(new FileOutputStream(new File(savestr), true));
}
else {
out = new PrintWriter(savestr);
}
out.append(mapstring);
out.close();
For better resource handling use Java 7 - The try-with-resources Statement
PrintWriter not appending content in the right order
It's better not to use a Writer
in each method here. Use a single StringBuilder
to append the content and pass it through the methods. It could be that the Writer
is not properly flushing the contents in the order in which content is appended. Specifically, the statement write.close()
inside innerwriter
would flush the contents of the inner object before the "String\r\n"
is actually written by the Writer
in the caller method.
You can avoid creating multiple Writer
s and use a StringBuilder
instead:
// pass a StringBuilder to append
public void innerwriter(StringBuilder sb) {
sb.append(this objects arg);
}
And when you're done with appending all content, write it using the Writer
created only once:
PrintWriter write = new PrintWriter(new FileOutputStream(path,
append));
StringBuilder sb = new StringBuilder();
for (SuperObject o : this.list) {
if (o instanceof Object1) {
((subObject1) w).writer1(sb);
}
if (o instanceof Object2) {
((subObject3) w).writer2(sb);
} if (o instanceof Object3) {
((subObject3) w).writer3(sb);
}
}
write.append(sb.toString());
write.close();
PrintWriter appending lines after every execution (Not refreshing the file)
My Suggestion is to use FileWriter
like
Following syntax creates a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
FileWriter(String fileName, boolean append)
set boolean to false
to indicate you do not want to do the append.
for example:
try (PrintWriter out = new PrintWriter(new FileWriter("login.txt", false));) {
for (int i = 0; i < 10; i++) {
out.println(i);
}
} catch (IOException e) {
System.out.println(e);
}
Read About The Try-With-Resources
FileWriter not appending to existing file
I wrote here few thoughts looking your code.
Remember to always close the object Reader
and Writer
.
Have a look at try-with-resources statement :
try (Writer writer = new BufferedWriter(new FileWriter("tweets.txt", true))) {
writer.write(mentionString);
} catch (IOException e) {
// Print error + stacktrace
}
To read an entire file in a List<String>
:
List<String> lines = Files.readAllLines(Paths.get("tweets.txt"), StandardCharsets.UTF_8);
And again, I think it's a bad practice write in the same file you're reading of.
I would suggest to write in a different file if you don't have a particular constraint.
But if you really want have this behavior there are few alternative.
- Create a temporary file as output and, when you process is successfully completed, than move it to the old one using
Files.move(from, to)
.
How to append text to an existing file in Java?
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
Java 7+
For a one-time task, the Files class makes this easy:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful: The above approach will throw a NoSuchFileException
if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE
and APPEND
options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter
is faster:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Notes:
- The second parameter to the
FileWriter
constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.) - Using a
BufferedWriter
is recommended for an expensive writer (such asFileWriter
). - Using a
PrintWriter
gives you access toprintln
syntax that you're probably used to fromSystem.out
. - But the
BufferedWriter
andPrintWriter
wrappers are not strictly necessary.
Older Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
Appending to a file is not working
Just tested your code and it's working fine. Can you post your full code ? Also how are you calling the writeLog method.
public class Test {
void writeLog(String s) {
try {
String filename = "C:\\Temp\\Logs.txt";
FileWriter fw = new FileWriter(filename, true);
fw.write(s + "\n");
fw.close();
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
}
public static void main(String[] args) {
Test t1 = new Test();
for (int i = 0; i < 5; i++) {
t1.writeLog("Hello");
}
}
}
This code creates a Logs.txt with the following content -
Hello
Hello
Hello
Hello
Hello
Related Topics
How to Remove Special Characters from a String
Where Do I Find a Standard Trie Based Map Implementation in Java
Alert Handling in Selenium Webdriver (Selenium 2) with Java
Java Calendar, Date, and Time Management for a Multi-Timezone Application
Spring Aop Not Working for Method Call Inside Another Method
Jvm Takes a Long Time to Resolve Ip-Address for Localhost
How to Create Custom Methods for Use in Spring Security Expression Language Annotations
Why Won't This Generic Java Code Compile
How to Show/Hide a Column at Runtime
How to Import Org.Openqa.Selenium.Webdriver Using Selenium and Java 11
Are Static Variables Shared Between Threads
Clone() VS Copy Constructor VS Factory Method
Why Does Math.Round(0.49999999999999994) Return 1
Warning About Ssl Connection When Connecting to MySQL Database