How to make PrintWriter overwrite old file - java

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 ).

Related

file input out append

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.

Write some text to a File - Exception

I want to write data to a text file. But, in my application, i will want to keep on writing items to the text file (Which means, the text that i want to write, should be appended to the file - and not create a new file every time)
My code, is as follows; But how could i append text the next time i am writing something to the file ?
1.) The problem with the code below is, the first time writes to the file, but when i am trying to write for the 2nd time i get the following exception;
java.io.IOException: Stream closed
2.) I want to be able to write to the same file untill the application is closed. Therefore, how can i close the Stream when the application is closed ?
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public void writeToFile(String stuff) {
try {
File file = new File("../somefile.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(stuff);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UPDATE 1
private File file;
public WriteToFileExample(){
file = new File("../somefile.txt");
}
public void writeToFile(String stuff) {
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(stuff);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EXCEPTION
Exception in thread "main" java.lang.NullPointerException
at com.proj.example.Log.WriteToFile(WriteToFileExample.java:3)
Which points to if (!file.exists()) {.
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
Use the true argument for the FileWriter constructor.
You should create your FileWriter using the contructor that takes an extra boolean argument, that indicates that you want to append.
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
You never close the FileWriter in your code. And from the documentation for the class:
Whether or not a file is available or may be created depends upon the
underlying platform. Some platforms, in particular, allow a file to be
opened for writing by only one FileWriter (or other file-writing
object) at a time. In such situations the constructors in this class
will fail if the file involved is already open.
Close the file writer before exiting your method, its good practice anyway. And yes, definitely do open the writer in append mode, if you don't want the files contents to be blown away every time you call your method.
Checking the api, says that the FileWriter constructor takes a boolean to flag whether to append or not. That answer your question?
Instead of doing this:
FileWriter fw = new FileWriter(file.getAbsoluteFile());
do as follow:
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
As to append on a existing file FileWriter needs an extra argument as true here
FileWriter
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.
Parameters:
file - a File object to write to
append - if true, then bytes will be
written to the end of the file rather than the beginning
Throws:
IOException - if the file exists but is a directory rather than a
regular file, does not exist but cannot be created, or cannot be
opened for any other reason
Since:
1.4

Outputting a String into a file, without clearing the file

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

How to skip a number of lines when writing to a txt file

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.

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