Overwrite and append in existing file - java

How to ovewrite existing file and then appending on it.
BufferedWriter outStream= new BufferedWriter(new FileWriter("encoded.txt", true));
It just append lines in it.
I want whenever outStream gets created, it overwrite the existing file then keep appending until the code is finished.
Any idea how to perform this action ?

Related

How to write to a file without deleting privious existing data [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 7 years ago.
I am try to write data to a text file. I am using this code:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");
}
But while the program is running, the file is overwriting the exist data that are already found in the text file. How can i write new data lines to the same text file without overwriting it ? Is there any easy and simple way to write it?
try (Writer writer = Files.newBufferedWriter(
Paths.get("filename.txt"), StandardCharsets.UTF_8,
StandardOpenOption.WRITE,
StandardOpenOption.APPEND)) {
writer.write("something");
}
The open options are a varargs list, and default to new file creation.
BTW FileWriter uses the platform encoding, so you where right to not use that class. It is not portable.
I think you may use 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.

Best strategy to add lines of text to a text file

I'm using txt files, creating them with the class PrintWriter. This allows me to print inside a txt file some content using println(...) method.
But now I need to add some content at the end of the list that I created. Like this:
PrintWriter writer = new PrintWriter("File.txt", "UTF-8");
writer.println("Hello");
writer.println("Josh!");
writer.close();
the result is a file like this:
Hello
Josh!
but what if I would like to add new words at the bottom of the text? I would prefer an overwriting of the file "File.txt" with the content updated?
Hello
Josh!
How are you?
I was thinking on something like, "Ok I have to add another line at the end, so read all the file, and write another file (with the same name and content) adding a new line at the end", but it seems too strange to do, I feel like there is another simple way to do it. Any other idea?
You could simply use a FileWriter instead, it has an append mode that you can enable:
FileWriter writer = new FileWriter("File.txt");
writer.write("Hello\n");
writer.write("Josh!\n");
writer.close();
writer = new FileWriter("File.txt", true);
writer.append("Great!");
writer.close();
Your suspicions are correct.
You should use try with resources (Java 7+):
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("File.txt", true)))) {
out.println("How are you?");
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
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.
Also this allows you to append to a file, rather than replacing the whole file, on every run. Lastly, try with resources means you do not have to call .close(), it's done for you! Grabbed from here

BufferedWriter to write to file

I am reading a file using BufferedReader in java. Here are the sequence of operations that I am trying to do as reading the file
Keep reading up to certain length of characters in the file
Once it reads up to the length, do some manipuation on the read string
Write the read string to a temp file
Reset all the counters (ex. counter of the length)
Go back #1 and do this again for rest of file
What I am trying to figure out is #3. I want to append to temp file as I am writing to file using BufferedWriter. I know there is append() but, that looks like it write to new line. However, I want to write to next cursor each time. Basically, i want to preserve the format of the original file. Make a exact same file except some value being changed.
I hope this make sense.
thanks.
You can use a FileWriter by passing true as the second argument to its constructor. This will cause the FileWriter to append to the end of the file rather than overwrite the existing contents.
http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
//calls to write will now append
append() will work just fine. You could even do just plain write(). If you want to write a new line with a BufferedWriter you would do this
BufferedWriter buff = new BufferedWriter();
buff.newLine();
For writing you can use PrintWriter
java.io.PrintWriter pw = new PrintWriter(new FileWriter(file, true));

File and Filewriter

I need a way to delete a line, im using this to write on the file:
FileWriter insert = new FileWriter(file, true);
PrintWriter out = new PrintWriter(insert);
out.println("1. Mario");
I made a thing that reads line by line but i've no idea how to delete the string that returns, is that even possible?
While you're reading in the lines of text write then lines you want to keep to a StringBuffer or StringBuilder then write the contents of the buffer/builder back to the file. Is there any specific reason that you're opening up the file for appending when you're wanting to remove lines of text from the file or am I missing something?

create a new and unique file each time one function is compiled in java

create a new and unique file each time the function is compiled.
that means if file exists already before execution of the program
then
it should delete the file and create a new file and append the new data.
or
add the content after just deleting the complete data which is already there in the same file.
I have created something like this....
Writer output = new BufferedWriter(new FileWriter("C:\\" + bankAccNo + ".txt", true));
output.append(myRow.getCell(0).toString()+ "\n");
output.close();
If you want to overwrite the file contents every time you write to it, use false for the append switch.
new FileWriter("<file>", false);

Categories