How to write more than once to text file using PrintWriter - java

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.

Related

How to use tables and .txt in Java?

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

After creating file using java, there were no values in it

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)

do not the overwrite with BufferedWritter

I created an object of a class in java and wrote information of this object in a file with BufferedWriter.
But when I create a new object and write information of this in the file, I lose the previous information of previous object.
How can I write in the file with BufferedWriter without overwriting a file?
If you use the FileWriter class it allows you to specify if you want to overwrite or append to the file in the constructor.
If you would like to append to a file that already exists, you can use the following:
BufferedWriter bW = new BufferedWriter(new FileWriter(new File("file.txt"), true));
Java default is overwriting the file. You can specify that you wish to append to a file.
boolean append=true;
FileWriter writer = new FileWriter(new File("yourfile.txt"),append);
BufferedWriter w = new BufferedWriter(writer);
// do your writing stuff

How to write new line in Java FileOutputStream

I want to write a new line using a FileOutputStream; I have tried the following approaches, but none of them are working:
encfileout.write('\n');
encfileout.write("\n".getbytes());
encfileout.write(System.getProperty("line.separator").getBytes());
This should work. Probably you forgot to call encfileout.flush().
However this is not the preferred way to write texts. You should wrap your output stream with PrintWriter and enjoy its println() methods:
PrintWriter writer = new PrintWriter(new OutputStreamWriter(encfileout, charset));
Alternatively you can use FileWriter instead of FileOutputStream from the beginning:
FileWriter fw = new FileWriter("myfile");
PrintWriter writer = new PrintWriter(fw);
Now just call
writer.println();
And do not forget to call flush() and close() when you finish your job.
It could be a viewer problem... Try opening the file in EditPlus or Notepad++. Windows Notepad may not recognize the line feed of another operating system. In which program are you viewing the file now?
String lineSeparator = System.getProperty("line.separator");
<br>
fos.write(lineSeparator.getBytes());
To add a line break use
fileOutputStream.write(10);
here decimal value 10 represents newline in ASCII

How to update files without losing previously written info?

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.

Categories

Resources