Java FileWriter with append mode - java

I'm currently using FileWriter to create and write to a file. Is there any way that I can write to the same file every time without deleting the contents in there?
fout = new FileWriter(
"Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt");
fileout = new PrintWriter(fout,true);
fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n");
fileout.close();

Pass true as a second argument to FileWriter to turn on "append" mode.
fout = new FileWriter("filename.txt", true);
FileWriter usage reference

From the Javadoc, you can use the constructor to specify whether you want to append or not.
public FileWriter(File file,
boolean append)
throws IOException
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be
written to the end of the file rather
than the beginning.

You can open the FileWriter in append mode by passing true as the second parameter:
fout = new FileWriter("Distribution_" + ... + ".txt", true);

You may pass true as second parameter to the constructor of FileWriter to instruct the writer to append the data instead of rewriting the file.
For example,
fout = new FileWriter(
"Distribution_" + Double.toString(lowerBound) + "" + Double.toString(_highBound) + ".txt",true);
Hope this would solve your problem.

Related

How to put multiple input in text file in java with gui [duplicate]

I'm currently using FileWriter to create and write to a file. Is there any way that I can write to the same file every time without deleting the contents in there?
fout = new FileWriter(
"Distribution_" + Double.toString(_lowerBound) + "_" + Double.toString(_highBound) + ".txt");
fileout = new PrintWriter(fout,true);
fileout.print(now.getTime().toString() + ", " + weight + ","+ count +"\n");
fileout.close();
Pass true as a second argument to FileWriter to turn on "append" mode.
fout = new FileWriter("filename.txt", true);
FileWriter usage reference
From the Javadoc, you can use the constructor to specify whether you want to append or not.
public FileWriter(File file,
boolean append)
throws IOException
Constructs a FileWriter object given a File object. If the second
argument is true, then bytes will be
written to the end of the file rather
than the beginning.
You can open the FileWriter in append mode by passing true as the second parameter:
fout = new FileWriter("Distribution_" + ... + ".txt", true);
You may pass true as second parameter to the constructor of FileWriter to instruct the writer to append the data instead of rewriting the file.
For example,
fout = new FileWriter(
"Distribution_" + Double.toString(lowerBound) + "" + Double.toString(_highBound) + ".txt",true);
Hope this would solve your problem.

How to make PrintWriter overwrite old file

I'm working on a project where I need to print some data to a file. During debugging phase, I would like to overwrite the old textfile so that I don't have to delete the old file just to see the result of some changes that I've made in the code. Currently, the new output data is either added to the old data in the file, or the file doesn't change at all (also, why could this be?). The following is, in essence, the printing part of the code:
public class Test {
public static void main(String[] arg) {
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream("Foo.txt", true));
} catch (Exception e){}
double abra = 5;
double kadabra = 7;
pw.printf("%f %f \n", abra, kadabra);
pw.close();
}
}
Thanks!
Pass false to the append parameter to overwrite the file:
pw = new PrintWriter(new FileOutputStream("Foo.txt", false));
Passing true for the second parameter indicates that you want to append to the file; passing false means that you want to overwrite the file.
Simply pass second parameter false.
Also you can use other writer object instead of FileOutputStream as you are working with txt file. e.g
pw = new PrintWriter(new FileWriter("Foo.txt", false));
or
pw = new PrintWriter(new BufferedWriter(new FileWriter("Foo.txt", false)));
while working with txt/docs files we should go for normal writer objects( FileWriter or BufferedWriter) and while working with binary file like .mp3 , image, pdf we should go for Streams ( FileOutputStream or OutputStreamWriter ).

Error when Saving and writing text files while program is in jar

Hello I am making a addon for bukkit a minecraft server modding program. This program requires me to put a jar into a foulder with an addon text document to provide class locations anyway. Then it uses my class and cast it into the class into the a class that it requires my class to inherit from. I am trying to write a text file in the same directory as my program so i wrote this(it is for a money program) (playerName is a pramater i used it as the filename because it is the player you are keeping balance for)
try{
FileWriter fstream = new FileWriter(new File(".").getAbsolutePath()+File.separator+playerName + ".txt",true);
getLogger().log(Level.INFO,"trying to save text document to " + new File("").getAbsolutePath()+File.separator+playerName + ".tct");
writer = new BufferedWriter(fstream);
writer.write("30");
return 30;
}
catch(Exception err){
getLogger().log(Level.INFO, "Exception occoured!{0}", err.getMessage());
return -1;
}
when i try to read it with this code it throws an exception
BufferedReader reader = new BufferedReader(new FileReader(new File(".").getAbsolutePath()+"/"+playerName));
Integer i = Integer.getInteger(reader.readLine());
return i.intValue();
Also i cannot find the text document it suposedly wrote. Any advice?
Also i would like to try to save it back a file so it is not saved in the .jar file but i dont know how to do that.
Also is there a possibility it is saving the file in the folder that the program that is using the class? Thanks XD
That’s the strangest thing I’ve seen for long:
FileWriter fstream = new FileWriter(new File(".").getAbsolutePath()+File.separator+playerName + ".txt",true);
getLogger().log(Level.INFO,"trying to save text document to " + new File("").getAbsolutePath()+File.separator+playerName + ".tct");
Try to clean up:
File f=new File(playerName + ".txt");
FileWriter fstream = new FileWriter(f, true);
getLogger().log(Level.INFO,"trying to save text document to " + f.getAbsolutePath());
Next thing: you should always close files after working with then.
Then your file names do not match. One time it is playername+".txt" the next time it is just playername
But the biggest mistake:
Integer i = Integer.getInteger(reader.readLine());
return i.intValue();
Integer.getInteger does not parse the string. It will look for a system property of that name (you won’t have a system property named "30") and interpret this as integer if it exists. In your case it will return null thus you get a NullPointerException when calling intValue on it. Use Integer.parseInt instead:
try(BufferedReader reader = new BufferedReader(new FileReader(playerName+".txt"))) {
Integer i = Integer.parseInt(reader.readLine());
return i.intValue();
}

Overwriting a text file when i don't want it to. - Java

I am working on a log file that is currently over-writing itself every single time. Now The thing is all i want it to do is to just write on the first line and append the list below to show the history from newest to oldest. Problem is I am not sure how to go about it I am looking at the code but don't know what I am doing wrong. Here is the code not sure if I am missing something or not.
String historylog = new Date().toString();
BufferedWriter bw = null;
String filepath = "C:\netbeans\Source code\test3";
String filename = "PatchHistory.log";
try
{
if (!(new File( filepath).exists()))
(new File( filepath)).mkdirs();
bw = new BufferedWriter( new FileWriter( filepath + File.separator
+ filename, true));
bw.write( historylog + "\r\n");
bw.newLine();
bw.flush();
bw.close();
return true;
}
catch (IOException){
return false;
}
Any Help would be appreciated not sure what I am doing wrong with this.
If I have understood you, you want to add log entries at the beginning of a log file.
AFAIK, (if you know any exceptions please tell me) all filesystems add data to the end of file. And Direct Access would overwrite the beginning of the file.
Your best option would be writting the log to a different file and, after writting what you want, write after that the contents of the original log file. Once done, close both files and overwrite the old file with the new one.
In your code
You are wrong here, you didn't used if statement properly.
if (!(new File( filepath).exists()))
(new File( filepath)).mkdirs(); // file path not exist, then it will execute
bw = new BufferedWriter( new FileWriter( filepath + File.separator + filename, true)); // this append file will always execute
Solution
if (!(f.exists())) {
//create new file
bw = new BufferedWriter(new FileWriter(filepath + File.separator + filename, false));
}
else{
//append in existing file
bw = new BufferedWriter(new FileWriter(filepath + File.separator + filename,true));
}

How do you append to a text file instead of overwriting it in Java?

I am trying to add a line to a text file with Java. When I run my program, I mean to add a simple line, but my program is removing all old data in the text file before writing new data.
Here is the code:
FileWriter fw = null;
PrintWriter pw = null;
try {
fw = new FileWriter("output.txt");
pw = new PrintWriter(fw);
pw.write("testing line \n");
pw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(FileAccessView.class.getName()).log(Level.SEVERE, null, ex);
}
Change this:
fw = new FileWriter("output.txt");
to
fw = new FileWriter("output.txt", true);
See the javadoc for details why - effectively the "append" defaults to false.
Note that FileWriter isn't generally a great class to use - I prefer to use FileOutputStream wrapped in OutputStreamWriter, as that lets you specify the character encoding to use, rather than using your operating system default.
Change this:
fw = new FileWriter("output.txt");
to this:
fw = new FileWriter("output.txt", true);
The second argument to FileWriter's constructor is whether you want to append to the file you're opening or not. This causes the file pointer to be moved to the end of the file prior to writing.
Use
fw = new FileWriter("output.txt", true);
From JavaDoc:
Constructs a FileWriter object given a
File object. If the second argument is
true, then bytes will be written to
the end of the file rather than the
beginning.
Two options:
The hard way: Read the entire file, then write it out plus the new data.
The easy way: Open the file in "append" mode: new FileWriter( path, true );

Categories