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)
Related
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();
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();
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);
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
Everytime I re-ask the user to enter their grades, I have it write a string to the file gradeReport, but everytime the while loop repeats, the previous result is erased. HOw do I get several lines outputted in the file?
//Open file and call writeToFile method
PrintWriter outputFile= new PrintWriter("gradeReport.txt");
outputFile.println(s.writeToFile());
outputFile.close();
And the method:
public String writeToFile()
{
DecimalFormat f = new DecimalFormat("0.00");
String str= name + "--" + id + "--" + f.format(getPercentage())+ "--" + getGrade();
return str;
}
Wrap the PrintWriter around a FileWriter that is set to append to the file.
PrintWriter outputFile= new PrintWriter(new FileWriter("gradeReport.txt", true));
Note 1: the FileWriter constructor's second parameter of true means that it is set to append to the file rather than to over-write the file.
Note 2: this question will likely and appropriately be closed soon as a duplicate.
Try using the constructor
FileWriter(String filename, boolean append)
to open the file in append mode.
FileWriter fw = new FileWriter("filename.txt", true);
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.