This question already has answers here:
How do I save a String to a text file using Java?
(24 answers)
Closed 7 years ago.
Wanna save some information that I parse from a JSON to a plain text into a file and I also want this information to not be overwritten every time you run the program. It's suppose to work as a simple error logging system.
So far have I tried this:
FileWriter fileWriter = null;
File file = new File("/home/anderssinho/bitbucket/dblp-article-analyzer/logg.txt");
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
...
String content = "------------------------------------";
fileWriter = new FileWriter(file);
fileWriter.write(content);
//fileWriter.write(obj.getString("title"));
//fileWriter.write(obj.getString("creators"));
//fileWriter.write(article.GetElectronicEdition());
But when I do this it seems that I overwrite the information all the time and I'm also having problem to save the information I wanna grab from the JSON-array that I've got.
How can I do to make this work?
FileWriter fooWriter = new FileWriter(myFoo, false);
// true to append
// false to overwrite;
where myFoo is the File name
See this link
use append:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("logg.txt", true)));
see this:
How to append text to an existing file in Java
Can you be more elaborate on this? If the problem is just not able to append then you can just add an argument to the FileWriter saying it to append and not write from the beginning.
Check the constructor here:
public FileWriter(String fileName, boolean append) throws IOException
Official Java Documentation:
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Throws:
IOException - if the named 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
Related
Whenever the next segment of code is run, I get the new csv file created, but I don't get anything written to it:
PrintWriter fout = null;
try {
// create file
fout= new PrintWriter("EEGLogger.csv");
String headerFile = "IED_COUNTER, IED_INTERPOLATED, IED_RAW_CQ, IED_AF3, IED_F7, IED_F3, IED_FC5, IED_T7, " +
"IED_P7, IED_O1, IED_O2, IED_P8, IED_T8, IED_FC6, IED_F4, IED_F8, IED_AF4, " +
"IED_GYROX, IED_GYROY,IED_TIMESTAMP";
// Writes the header to the file
fout.println(headerFile);
fout.println();
...
I do a fout.close() in a finally statement, but that still doesn't help get any output to the file. Any ideas here?
Either:
You are looking in the wrong place, i.e. not the current working directory, or
You don't have write access to the current working directory.
If you had used a FileWriter and not got an IOException, that would rule out (2).
I've seen about a million answers and comments here this week claiming that the current working directory equals the location of the JAR file, but it doesn't.
You could open a FileWriter
fout = new PrintWriter(new FileWriter("EEGLogger.csv"));
...
fout.flush();
fout.close()
I believe the PrintWriter is intended for formatting and character encoding. api docs states Prints formatted representations of objects to a text-output stream and as well Methods in this class never throw I/O exceptions.
Using the FileWriter as parameter would force you to handle any IOException that may happen so if the file is not created or not writable, you will immediately get this information.
Another situation can happen if the file is created and you are just looking for the file at incorrect location. I'd suggest to create a File object too, to see where the file really resides (what's your real working directory)
File f = new File("EEGLogger.csv");
fout = new PrintWriter(new FileWriter(f));
System.out.println(f.getAbsolutePath());
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 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.
This code appends to an already created Excel file:
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls");
What can we add / modify so that Decrypted.xls should be created if not already created and appended if already created?
You want the FileOutputStream(File file, boolean append) constructor for switching on whether you truncate or append.
According to the Javadocs for the String-accepting constructor of FileOutputStream, rover12, if the file doesn't already exist then it's created. Are you not seeing this behavior?
(And as others have mentioned, be sure to use the constructor that takes the second boolean argument so you can specify that you want to append the file if it already exists...)
Use the constructor:
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls", true);
to append to an existing file, if it doesn't exist. Your example will overwrite the existing one.
I want create text file but if the file already exists it should not create new file but should append the text to the content (at the end) of the existing file. How can I do it in Java?
for every one second I'm reading data from inputstream when i stop reading and again i start reading data at that time i should write to same file if file already exist
does I have to check the condition:
if(file.exists){
} else{
new File();
}
What I have to do?
You can use the following code to append to a file which already exists -
try {
BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
out.write("data");
out.close();
} catch (IOException e) { }
If the second argument in FileWriter's constructor is true, then bytes will be written to the end of the file rather than the beginning.
Quoting Stephen's comment:
...passing true as the 2nd
argument causes the file to be created
if it doesn't exist and to be opened
for appending if it does exist.
do i have to check the condition
if(file.exists){ }else{ new File(); }
No you don't have to do that: see other answers for the solution.
Actually, it would be a bad idea to do something like that, as it creates a potential race condition that might make your application occasionally die ... or clobber a file!
Suppose that the operating system preempted your application immediately after the file.exists() call returns false, and gave control to some other application. Then suppose that the other application created the file. Now when your application is resumed by the operating system it will not realise that the file has been created, and try to create it itself. Depending on the circumstance, this might clobber the existing file, or it might cause this application to throw an IOException due to a file locking conflict.
Incidentally, new File() does not actually cause any file system objects to be created. That only happens when you 'open' the file; e.g. by calling new FileOutputStream(file);
If you wish to append to the file if it already exists there's no need to check for its existence at all using exists(). You merely need to create a FileWriter with the append flag set to true; e.g.
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("foo.txt", true)));
pw.println("Hello, World");
pw.close();
This will create the file if it does not exist or else append to the end of it otherwise.