I have a button in a GUI, and when the button is pressed the user has the ability to add information to a text file. I have this part setup fine, but the thing that is messing with me is that when the user writes to the file it erases all the info in the text file and the only line left is the new one that was just added. I need to add the information and still keep the original info in the text file. I thought the append command was able to do this, but I'm obviously doing something wrong. Any help would be awesome!
Here's my code:
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter("info.txt");
writer = new BufferedWriter(fWriter);
writer.append(javax.swing.JOptionPane.showInputDialog(this, "add info"));
writer.newLine();
writer.close();
} catch (Exception e) {
}
Use the constructor that takes a bool append parameter. See the javadocs for FileWriter for that.
fWriter = new FileWriter("info.txt", true);
You need writer.flush(). PrintWriter are auto flush by default but not Writers
Related
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 ).
I want to write in atext file incrementally, that is, write the first String, then the program should check that there is text and should go to next line to write the next string etc.
Any ideas?
I was thinking that somehow the program should check whether there is something written in the file and go to the first blank line. But I have no idea, with which statements to do that.
Alternatively, I can just add everything in a String and print it all together in the end.But I would prefer the first option..
You need to open file with append mode. For example
FileOutputStream fos = new FileOutputStream(pathtoFile, true);
fos.write("Your new content".getBytes());
Basically first check if a file is empty, if not then append your content to the end of the file.
BufferedReader br = new BufferedReader(new FileReader("path_to_File"));
if (br.readLine() == null) { //checks if file is empty
System.out.println("File is empty");
}
Then to append to the file you can do something like this:
FileWriter fWriter = new FileWriter(file.getName(),true);
BufferedWriter bWriter = new BufferedWriter(fWriter);
bWriter.write(data);
I've been working on sort of "logging" to text file using BufferedWriter and I came across a problem:
I run the following code.. fairly basic..
BufferedWriter out = new BufferedWriter(new FileWriter(path+fileName));
String str = "blabla";
out.write(str);
out.close();
and the next thing I know is that the entire file that had couple of lines of text has been cleared and only 'blabla' is there.
What class should I use to make it add a new line, with the text 'blabla', without having to get the entire file text to a string and adding it to 'str' before 'blabla'?
What class should I use to make it add a new line, with the text 'blabla', without having to get the entire file text to a string and adding it to 'str' before 'blabla'?
You're using the right classes (well, maybe - see below) - you just didn't check the construction options. You want the FileWriter(String, boolean) constructor overload, where the second parameter determines whether or not to append to the existing file.
However:
I'd recommend against FileWriter in general anyway, as you can't specify the encoding. Annoying as it is, it's better to use FileOutputStream and wrap it in an OutputStreamWriter with the right encoding.
Rather than using path + fileName to combine a directory and a filename, use File:
new File(path, fileName);
That lets the core libraries deal with different directory separators etc.
Make sure you close your output using a finally block (so that you clean up even if an exception is thrown), or a "try-with-resources" block if you're using Java 7.
So putting it all together, I'd use:
String encoding = "UTF-8"; // Or use a Charset
File file = new File(path, fileName);
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true), encoding));
try {
out.write(...);
} finally {
out.close()'
}
Try using FileWriter(filename, append) where append is true.
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//oh noes!
}
The above should work: Source Reference
I'm making a program that will output lines to a text file. I don't wish to overwrite the file, but that is what my current code does. I just want to go down the number of lines that are already there and write hello. Here is my code:
FileWriter fileWriter = new FileWriter(fileLocation, false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
while(numberOfLines > compareToNumOfLines) {
bufferedWriter.newLine();
compareToNumOfLines++;
}
bufferedWriter.write("hello");
bufferedWriter.close();
Unfortunately, this just creates spaces where the text used to be. What am I doing wrong?
Change
FileWriter fileWriter = new FileWriter(fileLocation, false);
to
FileWriter fileWriter = new FileWriter(fileLocation, true);
As explained in the documentation, the second argument is a boolean that specify if you want to append the text or overwrite it.
If you want to append text to existing file then open the file in append mode. If you want to write at random place in file then you can use RandomAccessFile class.
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 );