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

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.

Related

Is there a way to write an empty file but still not create it? [duplicate]

This question already has answers here:
why new FileWriter("abc.txt") creates a new file and new File("abc.txt") does not?
(6 answers)
Closed 3 years ago.
I use new File() to create a file in memory and then I want to write on it but not creating file in disk.
File file = new File("hello.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("This is the text of my file");
writer.close();
I want it to not create a file on disk.
File is a filelocation, so it doesn't create a file, it point to one.
however when you create a filewriter, and write something to it (like in this example a with a wrapper class buffered writer)
then you will create an file, especially in your case you close the bufferedwriter, which prompts it to flush it's buffer to the filewriter. That filewriter is what's makes your file, cause it needs to write some data to the file called 'hello.txt'
the placement in your tomcatfolder(bin) is because that's what your current dir for the java application is.(startup of you jvm, and without changes to catalina.bat or .sh thats also your working dir)
equivalent is that you would touch a file in console, your working dir is where the file points toward, and unless you specify the full pathname the working directory will be used to place your file in.
If your looking for storing 'file' data in memory then take a look at https://stackoverflow.com/a/17595282/11515649

Writing string to file after particular string [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 7 years ago.
I want to write particular string in a file after a string. My file has this already -
##############################
path :
I need to write the String /sdcard/Docs/MyData after path :
Could anyone tell me how I could achieve this?
If I understand correctly you mean to append your path at the end of your file.
If so the use of a FileWriter is a good way to do it.
new FileWriter("Your path", true)
Notice that the boolean true in this case indicates that you want to append to your file, removing this altogether or using false instead would mean you want to overwrite the file.
An example for your case:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("C:/YourEpicPath/ThisFileNeedsSomeAppending.txt", true)))) {
out.println("/sdcard/Docs/MyData");
}catch (IOException e1) {
//exception handling left as an exercise for the reader
}
Here is some documentation if you need for android, normally there shouldn't be any big differences.

How to ensure overwriting doesn't happen while writing to text file from console in java? [duplicate]

This question already has answers here:
File Write - PrintStream append
(2 answers)
Closed 7 years ago.
I am trying to write the console output to the text file (Data.txt) so here is my code:
PrintStream out = new PrintStream(new File("/home/cse/Desktop/Data.txt"));
System.setOut(out);
out.print("");
When I run the program again after I have once run it, the output replaces the old data that was present in the Data.txt file. But I want it to continue adding the data from where it had stopped earlier. How can I do this?
You need to pass a FileOutputStream created with the constructor that accepts an append flag:
PrintStream out = new PrintStream(new FileOutputStream("/home/cse/Desktop/Data.txt", true));
The true states the new content will be appended to an existing file.
Using out.append() should do the job for you.
PrintStream out = new PrintStream(new File("/home/cse/Desktop/Data.txt"));
System.setOut(out);
out.append("");

RandomAccessFile setLength(0) adding a string of null characters to a file [duplicate]

This question already has answers here:
Clear contents of a file in Java using RandomAccessFile
(2 answers)
Closed 9 years ago.
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 to clear the file seems to be adding a string of null characters to the file (or perhaps it is the PrintWriter?) It only occurs if more text is added.
PrintWriter writer = new PrintWriter("temp","UTF-8");
while (condition) {
writer.println("Example text");
if (clearCondition) {
writer.flush();
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:
^#^#^#^#^#^#^#^#^#^#^#^#^#Text to be written onto the first line of temp file
The number of null characters is equal to the number of characters erased (including newline characters). If no new text is added to the file, it is completely blank.
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.
EDIT: I have no idea what caused those null characters. I realized I am stupid and there was no need to have a temp file, just a temp String with all the data that would later be written to a file. Strings are super easy to reset with = ""; Thanks for all the suggestions
It doesn't seem a good idea to have an opened PrintWriter on the file and use a RandomAccessFile at the same time.
If you close your writer and open a new one on the file (instead of using RandomAccessFile) I think it will suit your needs.

Most efficient way to write a string to a file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I save a String to a text file using Java?
I want to add a reading from a machine to a file (Java).
The reading will be in the form of a string that I have formatted. The file is just a text file. At the moment I am considering Filewriter/Buffered writer is this the correct one to use?
Use FileWriter will do you job.
BufferedWriter writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
// do stuff
writer.close();
If you are planning to use the JDK alone, you might want to consider wrapping your BufferedWriter with a PrintWriter as in
PrintWriter printWriter=new PrintWriter(bufferedWriter);
printWriter.println(yourString);
The printWriter comes with a nice println method.
Or if you are free to use external libraries, try FileUtils writeStringToFile
Yup. Use java.io.BufferedWriter.

Categories