Writing multiple lines to a file - java

I am trying to write timestamps to a file when clicking on a JButton. Once .close() is invoked the data is written to the file and any other writes throw an error. How can I write the data without have to create a new FileWriter and overwriting the previous line?

Instead of closing, which does this implictly, you call flush() on the FileWriter object. That keeps it open, but forces the data which has been buffered to be written to the file.
Don't forget to close() when you are done writing though.

You can either keep the writer open between clicks and close it at some other time (perhaps on form exit), or you can create a new FileWriter for each click and have it append to contents already in the file.
FileWriter writer = new FileWriter("output.txt", true); //true here indicates append to file contents
If you choose to keep the writer open between clicks, then you might want to call .flush() on each button press to make sure the file is up to date.

Try this,
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Wr {
public static void main(String[] args) throws IOException {
File f = new File("viv.txt");
FileWriter fw = new FileWriter(f, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Helloooooooooo");
bw.close();
}
}

Related

FileOutput Stream delets text file contents [duplicate]

This question already has answers here:
How to write data with FileOutputStream without losing old data?
(2 answers)
Closed 2 years ago.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class FileIoStream {
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\rs\\IO\\myfile.txt");
FileInputStream fis = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream(f);
}
}
Every time I make an object for FileOutputStream the contents in myfile.txt get deleted and I do not know why?
But when I just new FileInputStream it does not happen.
You should try with this constructor :
FileOutputStream fos = new FileOutputStream(f, true);
So what you have to add to the file will be appended if it already exists.
Doc available here
FileOutputStream by default overwrites the file if it exists. You can use the overloaded constructor to append to that file instead of overwriting it:
FileInputStream fis = new FileInputStream(f, true);
// Here -------------------------------------^
If gets deleted, because it actually gets overwritten. Every time you create a new FileOutputStream object with new FileOutputStream(File file) constructor, a new FileDescriptor is created, and therefore:
bytes are written to the beginning of the file.
You can think of it, like it starts writing to the file by overwriting everything that previously existed in that file.
You can alternatively create your FileOutputStream object with the FileOutputStream(File f, boolean append) constructor, passing true as a boolean argument into that constructor, and in this case:
bytes will be written to the end of the file rather than the beginning.
You will maintain whatever had been written into the file and your data will be appended to the existing data in the file.

Output to a file in java

How do I specify the path where I want to save my file when creating an output to a file in java?
//Set up Printer Output file
PrintWriter pw = new PrintWriter (new BufferedWriter (new FileWriter("project61.dat")));
For some reason after running my program, I don't see that my project61.dat file is created. I can't find anywhere in my C drive.
Simple google search yields helpful examples.
Here is one taken from here:
import java.io.IOException;
import java.io.PrintWriter;
public class MainClass {
public static void main(String[] args) {
try {
PrintWriter pw = new PrintWriter("c:\\temp\\printWriterOutput.txt");
pw.println("PrintWriter is easy to use.");
pw.println(1234);
pw.close();
} catch (IOException e) {}
}
}
If you use the following
//Set up Printer Output file
PrintWriter pw = new PrintWriter (new BufferedWriter (new FileWriter("project61.dat")));
Then it will create the file under your project. Please find the file where you project available.
If you want to write this file in a particular directory then mention the absolute path.
PrintWriter pw = new PrintWriter (new BufferedWriter (new FileWriter("c:\\project61.dat")));
pw.write("Test");
pw.close();
It will create the file under "C:" directory.
If you use the absolute directory "C://temp//project61.dat" then the temp folder must be available in c drive. The folder will not be created by default.

How to make PrintWriter overwrite old file

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 ).

How to download a website and put into another folder? java

I have this java code that download the .xml from my website and save it as an .xmlfile.
My problem is i want to save it into another folder.
When i run the code it downloads the file and saves it to the same folder where the java code is located.
I have searched about this and i cant find anything. Here is the code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
public class dlxml {
public static void main(String[] args)
throws Exception {
URL url = new URL("http://localhost:8080/lab/lab.xml");
BufferedReader reader = new BufferedReader
(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter
(new FileWriter("data.xml"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
}
}
So basically i want to download the file and save it to another folder. Is it possible?
and what if when i save it to a folder and there is the same file and name but i want to save it the same. For example i have data.xml save it to another folder but there is another same file with data.xml but i dont want it to be data(1).xml i want it to be data.xml
Thanks
Just define the folder path while writing to the file. As shown below:
BufferedWriter writer = new BufferedWriter(new FileWriter("\path\to\folder\data.xml"));
BufferedWriter writer = new BufferedWriter(new FileWriter(FULL_PATH));
In this code segment, you will want to change the file to use a path.
BufferedWriter writer = new BufferedWriter(new FileWriter("data.xml"));
By just using the name of the file, it will create the file in the relative directory (the same folder your code is running from) You'll want to change it to an absolute path so you can specify where you're storing it.

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

Categories