I use scanner & PrintWriter for files in JAVA. When i create a file & write some info in it & close it, next time i open the file & write something in it the previous info gets overwritten(previous info gets deleted). I need that information. Tell me a way so that i can write the info in file without overwriting(deleting)previous information.
You have to use :
new PrintWriter(new FileWriter(file , true));
Read the documentation of FileWriter(File file,boolean append)
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
FileWriter implements the Appendable interface.The second parameter to the FileWriter constructor will tell it to append to the file. It is responsible for being able to add some content to the end of particular file/stream.
Initialize your PrintWriter like this to append to the file
PrintWriter pw = new PrintWriter(new FileWriter(file, true));
Last param of the FileWriter is the append flag.
Related
Im building a Car Rental program and what I want it to, for now, is:
Register a user
Register a car
using .txt files to store the data.
With the code I've written, I can register only a single car and user. Every time I run the register method for client or car, the last register is erased.
Can you help me with this? Also, later I'm going to implement a way to rent a car, but I don't know how to do that also, so if you have any ideas of how to do it, please tell me!
Also I intend to do it without SQL or such things.
This is the code I'm using to register a user (I'm using netbeans with JForm):
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String nomeClient = txtNomeClient.getText();
String idClient = txtIdClient.getText();
File file = new File("clients.txt");
try {
PrintWriter output = new PrintWriter(file);
output.println(nomeClient);
output.println(idClient);
output.close();
JOptionPane.showMessageDialog(null, "Client registed!");
} catch (FileNotFoundException e) {
}
}
The problem is that you overwrite the existing file clients.txt, instead of appending to it by calling new PrintWriter(file). You can use the following code:
FileWriter fileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(fileWriter));
This way, you append the end of the file, see the constructor FileWriter(File file, boolean append). The documentation describes it perfectly:
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.
The FileWriter is just used to open a file in append mode, as PrintWriter does not have a suitable constructor to do that directly. You could also write characters with it, but a PrintWriter allows for formatted output. From the documentation of FileWriter:
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.
The PrintWriter uses the FileWriter passed in its constructor to append to the destination file, see here for a good explanation. As stated there, you could also use an FileOutputStream. There are multiple ways to do this.
Here is an example using a FileOutputStream and a BufferedWriter, which supports buffering and can reduce unnecessary writes that penalize performance.
FileOutputStream fileOutputStream = new FileOutputStream("clients.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(fileOutputStream);
PrintWriter printWriter = new PrintWriter(bufferedWriter);
I have created file using java, with following code
String Filecontent= "hei";
creating file
PrintWriter writer=new PrintWriter("D://balanworkspace//Coretest//Corejavatest//src//intvquestest//mydet3_8.txt","UTF-8");
printing the string
System.out.println(Filecontent);
writing to file
writer.println(Filecontent);
when I opened the file, there is no values. Why is it so?
You need to close the PrintWriter by doing this:
writer.close();
Make sure that the complete path of your file exists... If not, create a File and use mkdirs method to create it. After that, write with your PrintWriter
File f = null;
f = new File("yourpath");
Boolean bool = f.mkdirs();
You will need to flush the stream, for the values to appear in the file.
writer.flush()
Closing the stream will invoke the same,
writer.close()
If you don't want to use flush and close, you could pass in an argument "true" to the constructor of PrintWriter which will cause the output to be flushed each time println() is invoked.
PrintWriter(Writer out, boolean autoFlush)
I am trying to clear the contents of a file I made in java. The file is created by a PrintWriter call. I read here that one can use RandomAccessFile to do so, and read somewhere else that this is in fact better to use than calling a new PrintWriter and immediately closing it to overwrite the file with a blank one.
However, using the RandomAccessFile is not working, and I don't understand why. Here is the basic outline of my code.
PrintWriter writer = new PrintWriter("temp","UTF-8");
while (condition) {
writer.println("Example text");
if (clearCondition) {
new RandomAccessFile("temp","rw").setLength(0);
// Although the solution in the link above did not include ',"rw"'
// My compiler would not accept without a second parameter
writer.println("Text to be written onto the first line of temp file");
}
}
writer.close();
Running the equivalent of the above code is giving my temp file the contents:(Lets imagine that the program looped twice before clearCondition was met)
Example Text
Example Text
Text to be written onto the first line of temp file
NOTE: writer needs to be able to write "Example Text" to the file again after the file is cleared. The clearCondition does not mean that the while loop gets broken.
You want to either flush the PrintWriter to make sure the changes in its buffer are written out first, before you set the RandomAccessFile's length to 0, or close it and re-open a new PrintWriter to write the last line (Text to be written...). Preferably the former:
if (clearCondition) {
writer.flush();
new RandomAccessFile("temp","rw").setLength(0);
You'll be lucky if opening the file twice at the same time works. It isn't specified to work by Java.
What you should do is close the PrintWriter and open a new one without the 'append' parameter, or with 'append' set to 'false'.
How do I append text to a file in JavaIoFileSystemAccess?
I have tried calling the generateFile with the same filename, but it just overwrites the content of the file.
Is there a setting or method I can call to be able to append contents to a file?
You can use FileWriter class overloaded constructor for this.
FileWriter fileWriter = new FileWriter(new File("filepath in string"),true);
//second parameter specifies whether write this file
in append mode or normal mode
//true for append mode
I know how to create a PrintWriter and am able to take strings from my gui and print it to a text file.
I want to be able to take the same program and print to the file adding text to the file instead of replacing everything already in the text file. How would I make it so that when more data is added to the text file, it is printed on a new line every time?
Any examples or resources would be awesome.
try
{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println("the text");
out.close();
} catch (IOException e) {
}
The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file).
Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
PrintWriter writer=new PrintWriter(new FileWriter(new File("filename"),true));
writer.println("abc");
FileWriter constructor comes with append attribute,if it is true you can append to a file.
check this
Your PrintWriter wraps another writer, which is probably a FileWriter. When you construct that FileWriter, use the constructor that takes both a File object and an "append" flag. If you pass true as the append flag, it'll open the file in append mode, which means that new output will go at the end of the file's existing contents, rather than replacing the existing contents.