I want to write in a file but in a way that it should not delete existing data in that file rather it should append that file. Can anybody please help by giving any example related to appending a file? Thank you
You should use the FileWriter(File file, boolean append) constructor with the boolean value true.
Example
File file = new File("c:/tmp/foo.txt");
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
pw.println("Hello, World");
pw.close();
Related
Here is what I am working with basically (example file):
Line 1: 213124
Line 2: 243223
Line 3: 325425
Line 4: 493258
Line 5: 359823
Is there a way to make PrintWriter begin to write to a file with 5 lines shown above, but so that it only writes AFTER line 5? So like I want to use
PrintWriter log = new PrintWriter("blah.txt");
log.println("52525")
and I want it to write that to line 6, not overwrite line 1.
EDIT: For anyone with a similar problem, you want to figure out how to append your files. As of my writing this, two people showed how below
To append to an existing file use "append" mode:
FileOutputStream fos = new FileOutputStream(filename,true);
PrintWriter pw = new PrintWriter(fos);
The true argument to the FileOutputStream constructor sets append mode.
To append to a file, you need to use the FileWriter(String fileName, boolean append) constructor:
try (PrintWriter log = new PrintWriter(new FileWriter("blah.txt", true))) {
log.println("52525");
}
If you're going to write a lot of output, then a BufferedWriter may be good, and if you need to specify the character encoding, you need to wrap a FileOutputStream with an OutputStreamWriter. This makes the chain much longer:
try (PrintWriter log = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("blah.txt", true),
Charset.forName("UTF-8"))))) {
log.println("52525");
}
The PrintWriter(String fileName) you called is actually shorthand for:
new PrintWriter(new OutputStreamWriter(new FileOutputStream(fileName)))
How can I save multiple lines into One Text File?
I want to print "New Line" in the same Text File every time the code is executed.
try {
FileWriter fw = new FileWriter("Test.txt");
PrintWriter pw = new PrintWriter(fw);
pw.println("New Line");
pw.close();
}
catch (IOException e)
{
System.out.println("Error!");
}
I'm able to create a new file but can't create a new line every time the code is executed.
Pass true as a second argument to FileWriter to turn on "append" mode.
FileWriter fw = new FileWriter("filename.txt", true);
That will make your file to open in the append mode, which means, your result will be appended to the end of the file each time you'll write to the file. You can also write '\n' after each content writing so that it will inserts a new line there.
You are creating a new line every time it is run, the problem is that you are truncating the file when you open it. I suggest you append to the file each time.
try (FileWriter fw = new FileWriter("Test.txt", true); // true for append
PrintWriter pw = new PrintWriter(fw)) {
pw.println("New Line");
} // try-with-resource closes everything.
Note: openning and closing a file for each line is expensive, If you do this a lot I suggest leaving the file open and flushing the output each time.
You are doing this:
FileWriter fw = new FileWriter("Test.txt");
which is overwriting the file every time you execute that line...
BUT you need instead to append the data to the file
FileWriter fw = new FileWriter("Test.txt", true);
take a look at the constructor in the doc
You need to open the file in append mode. You can do that as follows:
FileWriter fw = new FileWriter("Test.txt", true);
Here is the documentation for the same.
I am working on a program that needs a lot of app data. I am trying to create a function that creates a file with the path/file name of the string path. Here's my code:
public static void CreateFile(String path) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(path, "UTF-8");
writer.close();
}
What did I do wrong? Shouldn't it create a file?
you can refer to this code :
FileWriter fw = new FileWriter("C:\\FileW3.txt");// you can give path here
//or
FileOutputStream fos = new FileOutputStream("path name");
PrintWriter pw = new PrintWriter (new OutputStreamWriter(fos));
pw.write("Combo stream and writer + using PrintWriter's write() methood/n");
pw.println();
pw.println("now using PrintWriter's println() methood");
pw.flush();
pw.close();
Also
File f = new File("path and filename");
This wont create a file , the file object can be used as parameter in FileWriter or FileOutputStream to create and then write to that file.
File object is just abstract representation of file.
It seems that you want to create an empty file. For this, you can use Files.createFile or File.createNewFile (but it will require you to instantiate a File).
To create a non-empty file, just write something in it and it will be automatically created if it does not exist.
Please see this link in the doucmentation - Create a file object then call 'createNewFile()' method on the newly created object.
I have a filewriter that takes String data from the user and writes it on the file. But the filewriter replaces the already existing data in that file. How do I prevent it from doing it? I just want to keep adding information without writing over something.
Here is the code
String info = scan.nextLine();
File myFile = new File ("/home/greg/workspace/Mavericks/fred.txt");
FileWriter writer = new FileWriter (myFile);
writer.write(register);
writer.flush();
Thanks. I fixed that. Now I just want to make the writer write using spaces. When I write to the file it just keeps writing within the same line.
You need use the boolean value true. From docs
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.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
Use second parameter of FileWriter, which is defining if you want to append or not. Just set it to true.
BufferedWriter writer = new BufferedWriter(new FileWriter(
sFileName, true));
Add \n after each line.
Use
new FileWriter(myFile, true)
The second parameter is for appending.
Api:
FileWriter(File file, boolean append)
Constructs a FileWriter object given a File object.
http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
FileWriter has an optional boolean in the constructor, which declares if it should be appended or not.
FileWriter writer = new FileWriter(..., true)
BufferedWriter bw = new BufferedWriter(new FileWriter(filename ,true));
I have a StringWriter variable, sw, which is populated by a FreeMarker template. Once I have populated the sw, how can I print it to a text file?
I have a for loop as follows:
for(2 times)
{
template.process(data, sw);
out.println(sw.toString());
}
Right now, I am just outputting to the screen only. How do I do this for a file? I imagine that with each loop, my sw will get changed, but I want the data from each loop appended together in the file.
Edit:
I tried the code below. When it runs, it does show that the file.txt has been changed, but when it reloads, the file still has nothing in it.
sw.append("CheckText");
PrintWriter out = new PrintWriter("file.txt");
out.println(sw.toString());
How about
FileWriter fw = new FileWriter("file.txt");
StringWriter sw = new StringWriter();
sw.write("some content...");
fw.write(sw.toString());
fw.close();
and also you could consider using an output stream which you can directly pass to template.process(data, os); instead of first writing to a StringWriter then to a file.
Look at the API-doc for the template.process(...) to find out if such a facility is available.
Reply 2
template.process(Object, Writer) can also take a FileWriter object, witch is a subclass of Writer, as parameter, so you probably can do something like that:
FileWriter fw = new FileWriter("file.txt");
for(2 times)
{
template.process(data, fw);
}
fw.close();
You can use many different streams to write to file.
I personally like to work with PrintWriter here
You can flag to append in the FileWriter (the true in the following example):
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
out.println(sw.toString());
out.close();
} catch (IOException e) {
// Do something
}
Why not use a FileWriter ?
Open it before you loop and generate your required output. As you write to the FileWriter it'll append to the buffer and write out your accumulated output upon a close()
Note that you can open a FileWriter in overwrite or append mode, so you can append to existing files.
Here's a simple tutorial.
If you don't mind using Apache commons IO :
FileUtils.write(new File("file.txt"), sw.toString(), /*append:*/ true);