FileOutput Stream delets text file contents [duplicate] - java

This question already has answers here:
How to write data with FileOutputStream without losing old data?
(2 answers)
Closed 2 years ago.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class FileIoStream {
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\rs\\IO\\myfile.txt");
FileInputStream fis = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream(f);
}
}
Every time I make an object for FileOutputStream the contents in myfile.txt get deleted and I do not know why?
But when I just new FileInputStream it does not happen.

You should try with this constructor :
FileOutputStream fos = new FileOutputStream(f, true);
So what you have to add to the file will be appended if it already exists.
Doc available here

FileOutputStream by default overwrites the file if it exists. You can use the overloaded constructor to append to that file instead of overwriting it:
FileInputStream fis = new FileInputStream(f, true);
// Here -------------------------------------^

If gets deleted, because it actually gets overwritten. Every time you create a new FileOutputStream object with new FileOutputStream(File file) constructor, a new FileDescriptor is created, and therefore:
bytes are written to the beginning of the file.
You can think of it, like it starts writing to the file by overwriting everything that previously existed in that file.
You can alternatively create your FileOutputStream object with the FileOutputStream(File f, boolean append) constructor, passing true as a boolean argument into that constructor, and in this case:
bytes will be written to the end of the file rather than the beginning.
You will maintain whatever had been written into the file and your data will be appended to the existing data in the file.

Related

Java - how to replace file contents? [duplicate]

This question already has answers here:
Is this the best way to rewrite the content of a file in Java?
(8 answers)
Closed 6 years ago.
I have a file that contains only a very small amount of information that needs to be updated periodically. In other words, I want to truncate the file before writing to it. The easiest solution I found was to delete and create it again as shown here:
File myFile = new File("path/to/myFile.txt");
myFile.delete();
myFile.createNewFile();
// write new contents
This 'works' fine, but is there a better way?
There is no need to delete the file and recreate one. If you are writing to the file, for instance using PrintWriter, it will overwrite your current file content.
Example:
public static void main(String[] args) throws IOException
{
PrintWriter prw= new PrintWriter (“MyFile.txt”);
prw.println("These text will replace all your file content");
prw.close();
}
It will only append to the end of the file if you use the overloaded version of the PrintWriter constructor:
PrintWriter prw= new PrintWriter (new FileOutputStream(new File("MyFile.txt"), true));
//true: set append mode to true
In the below example, the "false" causes the file to be overwritten, true would cause the opposite.
File file=new File("C:\Path\to\file.txt");
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(file,false));
String body = "new content";
outstream.write(body.getBytes());
outstream.close();

Saving to an object file in Java: getParentFile()

public void save() throws IOException {
File f = new File(path);
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
FileOutputStream fout = new FileOutputStream(f, false);//overwrite, append set to false
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(this.vehicles);
out.close();
}
I Have the following code that saves an object of type vehicule into a file. However, I don't understand quite well how it works since it was a sample provided for me, and since I am new in the java field.
I am wondering what is the interpretation of these lines if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
} I am wondering what getParentFile().exists() does and why are we searching for the parent file while we are interested in the file itself. same question for the next line: why are we interested in the parent directory when we are going to create the file?
I would like to know also the difference between FileOutputStream and ObjectOutputStream and why both are used one next to another in the following lines FileOutputStream fout = new FileOutputStream(f, false);//overwrite, append set to false
ObjectOutputStream out = new ObjectOutputStream(fout);
Thank you in advance
Files are pointers to file or directory locations on a File System. If you intend to write to a file, though, the parent directory in which it will reside must exist. Otherwise, you'll get an IOException. The mkdirs call will create the necessary parent directory (or directories) to avoid that IOException.
I don't think the exists check is really necessary, though, since the mkdirs method returns false if it actually didn't create anything.
Also, you should close your OutputStream within a finally block or use the Java 7 try-with-resources:
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f, false))) {
out.writeObject(vehicles);
}

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

Writing multiple lines to a file

I am trying to write timestamps to a file when clicking on a JButton. Once .close() is invoked the data is written to the file and any other writes throw an error. How can I write the data without have to create a new FileWriter and overwriting the previous line?
Instead of closing, which does this implictly, you call flush() on the FileWriter object. That keeps it open, but forces the data which has been buffered to be written to the file.
Don't forget to close() when you are done writing though.
You can either keep the writer open between clicks and close it at some other time (perhaps on form exit), or you can create a new FileWriter for each click and have it append to contents already in the file.
FileWriter writer = new FileWriter("output.txt", true); //true here indicates append to file contents
If you choose to keep the writer open between clicks, then you might want to call .flush() on each button press to make sure the file is up to date.
Try this,
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Wr {
public static void main(String[] args) throws IOException {
File f = new File("viv.txt");
FileWriter fw = new FileWriter(f, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Helloooooooooo");
bw.close();
}
}

How to save text file without overwriting?

I want to save in a text file without overwriting the current data. I mean the next data that will be save will go to the new/next line whenever I save and that is my problem, I don't know how to do that.
Could someone help me about this matter?
Here's the code in save() method :
public void save(String filename) throws IOException
{
FileOutputStream fOut = new FileOutputStream(filename);
ObjectOutputStream outSt = new ObjectOutputStream(fOut);
outSt.writeObject(this);
}
Read the docs
public FileOutputStream(File file, boolean append) throws FileNotFoundException
Creates a file output stream to write to the file represented by the
specified File object. If the second argument is true, then bytes will
be written to the end of the file rather than the beginning. A new
FileDescriptor object is created to represent this file connection.

Categories