Making a new line in a file [duplicate] - java

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 8 years ago.
Im trying to write a text to file, but it overwrites whats inside, can somebody explain how to check if the text exists and then put a new line and write? Here is the code I am working with:
try
{
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw =
new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.newLine();
bw.write(petName);
bw.close();
System.out.println("Done!");
}
catch (IOException exc)
{
System.out.println(exc);
}
Thank you for any kind of help.

how to check if the text exists and then put a new line and write?
Use File#length() to check if the text exists in the file.
if(file.length()>0){
bw.newLine();
}
Note:
Open the file in append mode if you don't want to override the existing content of the file.

Use following to append if file exists.
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

Related

Writing Multiple Lines to a File (.txt) in Java [duplicate]

This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 4 years ago.
I am new to File Streams and would appreciate some help. The following code is the code I use to write to a specified file.
OutputStream outStream = new FileOutputStream(file);
outStream.write(contentsToWrite.getBytes());
outStream.close();
How do I save different lines to a file? In my case using \n does not work when writing to a file.
How do I save a line to the file without deleting the other lines?
There is a nice, simple method which allows you to do this with a List of Strings you want to write and the file itself.
List<String> lines=new ArrayList<>(contentToWrite);//if it is an array or something that isn't a list
Files.write(file.toPath(),lines);
Java has some wrapper class to file streams. BufferedWriter can be used to write string to file.
boolean append = true;
String filename = "/path/to/file";
BufferedWriter writer = new BufferedWriter(new FileWriter(filename, append));
// OR: BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append)));
writer.write(line1);
writer.newLine();
writer.write(line2);
writer.newLine();
// ......
writer.close();
append meanings you write to the end of the file instead of empty the file.
The FileOutputStream class constructor method has the second parameter. if you set it to true. It will append the content the file you write. And "\r\n" can change to a new line.
OutputStream outStream = new FileOutputStream("a.txt",true);
outStream.write("hello".getBytes());
outStream.write("\r\n".getBytes());
outStream.write("hello".getBytes());
outStream.close();

How to make BufferedWriter not overwrite a text file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 5 years ago.
I am currently making an application where the user can add multiple accounts. The login information is being stored in a text file. I need a way for the user to add a new account without BufferedWriter overwriting the other accounts' information. Any suggestions?
package mainFiles.fileManagers;
import java.io.*;
public class NewTXT {
public static void nFile( String a , String b ) throws IOException {
File f = new File("mainFiles\\storage\\accountinfo.txt");
FileWriter writer = new FileWriter("mainFiles\\storage\\accountinfo.txt");
BufferedWriter bWriter = new BufferedWriter(writer);
f.createNewFile();
f.canWrite();
bWriter.newLine();
bWriter.write(a + "?" + b );
bWriter.newLine();
bWriter.close();
}
}
There is nothing wrong with the BufferedWriter. You have to construct the FileWriter in append mode:
FileWriter writer = new FileWriter("mainFiles\\storage\\accountinfo.txt", true);
Check the FileWriter documentation:
https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean)

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

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

How to add text to a text file in java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to append text to an existing file in Java
I want to add data to a text file. So it's one after another...so something like:
1
2
3
<add more here>
But I don't want the text from the file to be deleted at all. This is the code i'm using atm, but it replaces what ever is in the file. Could someone please tell me how to do what I asked. Thanks.
FileWriter fstream = new FileWriter("thefile.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("blabla");
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
use this
FileWriter fstream = new FileWriter("thefile.txt",true);
the explanation
public FileWriter(String fileName, boolean append) throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

Categories