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
Related
I am trying to write some coordinates to a file and later read it in as a string. So I need to have them written to file attached...without space or a new line, but my code writes only the first coordinate, that is pos_Let, but does not write pos_Num at all, not even with a space or on a new line.
So how can I get the code to write to file pos_LetposNum like that? Obviously I mean their references ;) ..thanks in advance
protected void writeCoordtoFile () throws IOException
{
File file = new File("FermiPresentCoord.txt");
boolean yes = file.createNewFile() ;
//boolean yes = exists();
if (yes == true)
{
// create a FileWriter Object
FileWriter writer = new FileWriter(file, true);
// Writes the content to the file
writer.write("");
writer.flush();
writer.write(pos_Let);
writer.flush();
writer.write(pos_Num);
writer.close();
}
else
{
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter out = new FileWriter(file);
// Writes the content to the file
out.write(pos_Let);
out.flush();
out.write(pos_Num);
out.flush();
out.close();
}
}
Quoting the method createNewFile():
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.
Returns:
true if the named file does not exist and was successfully created; false if the named file already exists
in your case, you first create the file, and createNewFile() returns true, so you go to the if block, appending the line to the current file. Then, createNewFile() returns false, since, the file exists! So, you go to the else block, and create the file again from scratch...
So, basically, just inverse the if with else, and don't call createNewFile() twice... With the least possible changes (so that you do not get confused) here is my simple suggestion:
protected void writeCoordtoFile () throws IOException
{
File file = new File("FermiPresentCoord.txt");
boolean fileDoesNotExist = file.createNewFile() ;
//boolean fileDoesNotExist = file does **not** exist!
if (fileDoesNotExist)
{
// create a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write(pos_Let);
writer.write(pos_Num);
writer.close();
}
else
{
// creates a FileWriter Object
FileWriter out = new FileWriter(file,true);
// Writes the content to the file
out.write(""); //not sure why you need that...
out.write(pos_Let);
out.write(pos_Num);
out.close();
}
}
I can not find out why you are checking the existence of the output file. Because, when you are using FileWriter if the file specified in the path does not exist, it would create it and open a character output stream to it. Also if it exists in that path, only opens the output stream and it is ready to write into.
Try the following code and see whats happening when you run it more than one times:
float posLat = 156.23589965f;
float posLon = 12.987564f;
File file = new File("c:/FermiPresentCoord.txt");
FileWriter writer = new FileWriter(file, true);
writer.append(posLat+",");
writer.append(posLon+",");
writer.flush();
writer.close();
There is no need to invoke the file.createNewFile() and/or checking the for the existence of the file when you want to write into it.
The second argument for the FileWriter constructor is append flag. So every time you create an output stream to a file with FileWriter(file, true) constructor it automatically appends to the data of the file.
Good Luck.
I'm parsing a file. I'm creating a new output file and will have to add the 'byte[] data' to it. From there I will need to append many many other 'byte[] data's to the end of the file. I'm thinking I'll get the user to add a command line parameter for the output file name as I already have them providing the file name which we are parsing. That being said if the file name is not yet created in the system I feel I should generate one.
Now, I have no idea how to do this. My program is currently using DataInputStream to get and parse the file. Can I use DataOutputStream to append? If so I'm wondering how I would append to the file and not overwrite.
If so I'm wondering how I would append to the file and not overwrite.
That's easy - and you don't even need DataOutputStream. Just FileOutputStream is fine, using the constructor with an append parameter:
FileOutputStream output = new FileOutputStream("filename", true);
try {
output.write(data);
} finally {
output.close();
}
Or using Java 7's try-with-resources:
try (FileOutputStream output = new FileOutputStream("filename", true)) {
output.write(data);
}
If you do need DataOutputStream for some reason, you can just wrap a FileOutputStream opened in the same way.
Files.write(new Path('/path/to/file'), byteArray, StandardOpenOption.APPEND);
This is for byte append. Don't forget about Exception
File file =new File("your-file");
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(your-string);
bufferWritter.close();
Of coruse put this in try - catch block.
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 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
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 );