How to write a program in Java to check the existence of a txt file if does not exist than create a new one else append the new txt in that file.
FileWriter fstream = new FileWriter("foo.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("foo bar");
out.close();
The second argumnet to FileWriter tells it to append.
Related
My code is when user type in the Name text filed, it will export as text file and record the Name.
For example,
I typed 1st time "James" in the Name text filed, it will appear
"James" in the text file. I type second time "Agnes" , it appears
"Agnes" in the text file. But It only appear one name in the text
file.
I want all the names appear whatever user type in the text filed.
How do i modify my codes?
try
{
new JTextField();
// create new file
String path="C:\\export.txt";
File file = new File(path);
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// write in file
// bw.write(txtName.getText());
if (txtName.getText() ==null)
{
bw.write(txtName.getText());
bw.write('\n');
System.out.print("1st Name:" +txtName.getText());
}
else
if (txtName.getText()!=null)
{
// bw.write('\n');
bw.write(txtName.getText());
System.out.print("2nd Name:" +txtName.getText());
}
// close connection
bw.flush();
bw.close();
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
Please advise.Thanks
You should use append mode when write file, like:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
Edit again:
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bw = new BufferedWriter(fileWritter);
if (txtName.getText()!=null){
//this line edited
bw.write(txtName.getText()+"\n");
System.out.print("2nd Name:" +txtName.getText());
}
I'm working on a project where I need to print some data to a file. During debugging phase, I would like to overwrite the old textfile so that I don't have to delete the old file just to see the result of some changes that I've made in the code. Currently, the new output data is either added to the old data in the file, or the file doesn't change at all (also, why could this be?). The following is, in essence, the printing part of the code:
public class Test {
public static void main(String[] arg) {
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream("Foo.txt", true));
} catch (Exception e){}
double abra = 5;
double kadabra = 7;
pw.printf("%f %f \n", abra, kadabra);
pw.close();
}
}
Thanks!
Pass false to the append parameter to overwrite the file:
pw = new PrintWriter(new FileOutputStream("Foo.txt", false));
Passing true for the second parameter indicates that you want to append to the file; passing false means that you want to overwrite the file.
Simply pass second parameter false.
Also you can use other writer object instead of FileOutputStream as you are working with txt file. e.g
pw = new PrintWriter(new FileWriter("Foo.txt", false));
or
pw = new PrintWriter(new BufferedWriter(new FileWriter("Foo.txt", false)));
while working with txt/docs files we should go for normal writer objects( FileWriter or BufferedWriter) and while working with binary file like .mp3 , image, pdf we should go for Streams ( FileOutputStream or OutputStreamWriter ).
I want to write in atext file incrementally, that is, write the first String, then the program should check that there is text and should go to next line to write the next string etc.
Any ideas?
I was thinking that somehow the program should check whether there is something written in the file and go to the first blank line. But I have no idea, with which statements to do that.
Alternatively, I can just add everything in a String and print it all together in the end.But I would prefer the first option..
You need to open file with append mode. For example
FileOutputStream fos = new FileOutputStream(pathtoFile, true);
fos.write("Your new content".getBytes());
Basically first check if a file is empty, if not then append your content to the end of the file.
BufferedReader br = new BufferedReader(new FileReader("path_to_File"));
if (br.readLine() == null) { //checks if file is empty
System.out.println("File is empty");
}
Then to append to the file you can do something like this:
FileWriter fWriter = new FileWriter(file.getName(),true);
BufferedWriter bWriter = new BufferedWriter(fWriter);
bWriter.write(data);
I'm making a program that will output lines to a text file. I don't wish to overwrite the file, but that is what my current code does. I just want to go down the number of lines that are already there and write hello. Here is my code:
FileWriter fileWriter = new FileWriter(fileLocation, false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
while(numberOfLines > compareToNumOfLines) {
bufferedWriter.newLine();
compareToNumOfLines++;
}
bufferedWriter.write("hello");
bufferedWriter.close();
Unfortunately, this just creates spaces where the text used to be. What am I doing wrong?
Change
FileWriter fileWriter = new FileWriter(fileLocation, false);
to
FileWriter fileWriter = new FileWriter(fileLocation, true);
As explained in the documentation, the second argument is a boolean that specify if you want to append the text or overwrite it.
If you want to append text to existing file then open the file in append mode. If you want to write at random place in file then you can use RandomAccessFile class.
I am trying to add a line to a text file with Java. When I run my program, I mean to add a simple line, but my program is removing all old data in the text file before writing new data.
Here is the code:
FileWriter fw = null;
PrintWriter pw = null;
try {
fw = new FileWriter("output.txt");
pw = new PrintWriter(fw);
pw.write("testing line \n");
pw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(FileAccessView.class.getName()).log(Level.SEVERE, null, ex);
}
Change this:
fw = new FileWriter("output.txt");
to
fw = new FileWriter("output.txt", true);
See the javadoc for details why - effectively the "append" defaults to false.
Note that FileWriter isn't generally a great class to use - I prefer to use FileOutputStream wrapped in OutputStreamWriter, as that lets you specify the character encoding to use, rather than using your operating system default.
Change this:
fw = new FileWriter("output.txt");
to this:
fw = new FileWriter("output.txt", true);
The second argument to FileWriter's constructor is whether you want to append to the file you're opening or not. This causes the file pointer to be moved to the end of the file prior to writing.
Use
fw = new FileWriter("output.txt", true);
From JavaDoc:
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.
Two options:
The hard way: Read the entire file, then write it out plus the new data.
The easy way: Open the file in "append" mode: new FileWriter( path, true );