I'm using txt files, creating them with the class PrintWriter. This allows me to print inside a txt file some content using println(...) method.
But now I need to add some content at the end of the list that I created. Like this:
PrintWriter writer = new PrintWriter("File.txt", "UTF-8");
writer.println("Hello");
writer.println("Josh!");
writer.close();
the result is a file like this:
Hello
Josh!
but what if I would like to add new words at the bottom of the text? I would prefer an overwriting of the file "File.txt" with the content updated?
Hello
Josh!
How are you?
I was thinking on something like, "Ok I have to add another line at the end, so read all the file, and write another file (with the same name and content) adding a new line at the end", but it seems too strange to do, I feel like there is another simple way to do it. Any other idea?
You could simply use a FileWriter instead, it has an append mode that you can enable:
FileWriter writer = new FileWriter("File.txt");
writer.write("Hello\n");
writer.write("Josh!\n");
writer.close();
writer = new FileWriter("File.txt", true);
writer.append("Great!");
writer.close();
Your suspicions are correct.
You should use try with resources (Java 7+):
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("File.txt", true)))) {
out.println("How are you?");
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file). Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out. But the BufferedWriter and PrintWriter wrappers are not strictly necessary.
Also this allows you to append to a file, rather than replacing the whole file, on every run. Lastly, try with resources means you do not have to call .close(), it's done for you! Grabbed from here
Related
I'm trying to keep a log of http responses with writing them in a txt file.
I'm using the FileWriter in Java, but unfortunately when the number of lines (e.g. 1000 lines) or the size of the txt file (e.g. 80kb) is exceeded, it automatically removes the previous content and writes the new ones.
This happens every time the limit is exceeded.
try{
File file = new File("response.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file,true);
writer.write(+System.currentTimeMillis()+"\t"+response+"\n");
writer.flush();
writer.close();}
catch(IOException ioe){
System.out.println("\nError");}
file.createNewFile();
Here you are creating a new file every time you call this method.
FileWriter writer = new FileWriter(file,true);
Here you are trying to append to an existing file, which no longer exists because of the prior File.createNewFile(). So you are losing all your prior output and writing to a new file every time you call this method. Remove it.
This kind of second-guessing is always and everywhere a complete waste of time and space. new FileWriter() already has to do all that anyway, and you're just forcing it to happen twice: in this case, erroneously.
In fact you should try to keep the file open rather than reopening and reclosing it every time you call this method. What you're doing is horrifically inefficient. As well as not working.
NB When you get an exception, print the exception. Not just "error". Otherwise next thing you know you will be asking here why it prints "error", just because you didn't write your code properly.
I am guessing it's either because:
There's not enough disk space.
file.createNewFile() is being used for every line and it's not reliable.
You open and close the stream for every line.
You call this code in a multithreaded environment without synchronising.
Try the following:
BufferedWriter out = null;
try
{
out = new BufferedWriter(new FileWriter(file, true));
out.append(response);
out.newLine();
} catch(Exception e)
{
e.printStackTrace(); // if needed
out.append("Error");
out.newLine();
}
finally
{
ResourceUtil.closeQuietly(out);
}
I'm simply trying to add a new line of text to my *.txt file, but nothing happens at all. The file is packed with a .war, so I use a ClassLoader to access the file. Also, both my eclipse IDE, and the contents of the file, use UTF-8 encoding.
I've used these for inspiration:
How to add a new line of text to an existing file in Java?
Java BufferedWriter object with utf-8
Now my code is mainly based on the last post, and looks like this:
public class test {
public static void main(String[] args){
URL url = Thread.currentThread().getContextClassLoader().getResource("MilestoneExport.txt");
File file = new File(url.getFile());
System.out.println(file.canRead()); //true
System.out.println(file.canWrite()); //true
try {
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
out.append("new line");
out.append("new line 2");
out.append("new line 3");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've confirmed that the file is in fact found, and it reads fine. I've been able to output the entire content of it to the console through the use of a BufferedReader. The path of the file is also correct, but absolutely no text is added to the file. I've made sure that I have refreshed and updated every time I've run the program.
Also, I've tried to create a simple empty file called foo.txt, which is located in the same directory as test.java. I added the following code to the main method, as provided by the BufferedWriter API, at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
PrintWriter out2 = new PrintWriter(
new BufferedWriter(new FileWriter("foo.txt")));
out2.println("new Line");
out2.close();
What am i missing here? Why are there no error messages, and no responses or feedbacks whatsoever?
EVERYTHING BELOW IS ONLY ADDITIONAL INFO ABOUT WHAT I'VE TRIED. NO FEEDBACK IN ANY CASES:
Not this one: Why is BufferedWriter not writing to file?
Not this one: why is bufferedwriter not writing in the file?
Not this one: Unable to write to file using BufferedWriter
Yet another "remember to close/flush": Java : Problems accessing and writing to file
Defining the BufferedWriter outside the try block makes no difference, but I tried it anyway, due to How to write detail into file using BufferedWriter and FileWriter in Java?
Also, this code, from this answer, does nothing as well...
try {
BufferedWriter output = new BufferedWriter(new FileWriter(new File("house.txt")));
output.write("text");
output.close();
}
catch (IOException e) {
e.printStackTrace();
}
last but not least, I suspected that it might have something to do with the packaging of my Web-App, and differences between the source and target-folders. So I copied the code to a brand new clean project, but it still does nothing at all...
EDIT:
this code:
System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
System.out.println(file.getName());
System.out.println(file.isDirectory());
System.out.println(file.isFile());
System.out.println(file.setLastModified(new GregorianCalendar().getTimeInMillis()));
gives these outputs:
true
D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
D:\Data\myworkspace\MyProject\target\classes\MilestoneExport.txt
MilestoneExport.txt
false
true
true
Am I completely misunderstanding the use of java's File-objects, and it's uses with FileWriters? The file is clearly 100% confirmed the correct file.
You should use the other constructor of FileOutputStream in order to open the file in append mode :
FileOutputStream(File file, boolean append)
I.e,
new FileOutputStream(file, true)
Since I can't comment, you might not be saving the file back into the archive it came from (I'm not sure if java supports writing to the internal structures of archives by editing the files that are included, however you might want to try to store the file externally to the archive to see if that is the place the issue comes from).
The cause of what you posted in the comments is that your IDE won't extract the resource file from a compiled program, if you want to sync the internal data you might be able to setup a client-server connection using sockets and creating a program that writes the data to the local file from data packets send to your web-app, otherwise retrieving the edited file from where you are hosting might be less complicated (or if you are deploying from the same PC you might be able to get away with a symbolic or hard link)
I've tried this code that is very similar to yours and it's working nicely,
so i think the problem is the way you are picking the path of the file.
public static void main(String[] args){
File file = new File("./localtest.txt");
System.out.println(file.canRead()); //true
System.out.println(file.canWrite()); //true
try {
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
out.append("new line");
out.append("new line 2");
out.append("new line 3");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
this works
PrintWriter pw= new PrintWriter(
new BufferedWriter(new FileWriter("C:\\foo.txt")));
pw.println("line 1");
pw.close();
I am reading a file using BufferedReader in java. Here are the sequence of operations that I am trying to do as reading the file
Keep reading up to certain length of characters in the file
Once it reads up to the length, do some manipuation on the read string
Write the read string to a temp file
Reset all the counters (ex. counter of the length)
Go back #1 and do this again for rest of file
What I am trying to figure out is #3. I want to append to temp file as I am writing to file using BufferedWriter. I know there is append() but, that looks like it write to new line. However, I want to write to next cursor each time. Basically, i want to preserve the format of the original file. Make a exact same file except some value being changed.
I hope this make sense.
thanks.
You can use a FileWriter by passing true as the second argument to its constructor. This will cause the FileWriter to append to the end of the file rather than overwrite the existing contents.
http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
//calls to write will now append
append() will work just fine. You could even do just plain write(). If you want to write a new line with a BufferedWriter you would do this
BufferedWriter buff = new BufferedWriter();
buff.newLine();
For writing you can use PrintWriter
java.io.PrintWriter pw = new PrintWriter(new FileWriter(file, true));
I have a slight delema with learning FileWriter... The ultimate goal is writing a program that will "spawn" a .bat file that will be executed by the batch code that launched the .jar. The problem is, I have no clue how to make sure that every FileWriter.write(); will print on a new line... Any ideas??
To create new lines, simply append a newline character to the end of the string:
FileWriter writer = ...
writer.write("The line\n");
Also, the PrintWriter class provides methods which automatically append newline characters for you (edit: it will also automatically use the correct newline string for your OS):
PrintWriter writer = ...
writer.println("The line");
Use a BufferedWriter and use writer.newLine() after every write-operation that represents one line.
Or, use a PrintWriter and writer.println().
If you are using BufferedWriter then you can use an inbuilt method :
BufferedWriter writer = Files.newBufferedWriter(output, charset);
writer.newLine();
...
Scanner scan = new Scanner(System.in);
System.out.println("Input : ");
String t = scan.next();
FileWriter kirjutamine = new FileWriter("...");
BufferedWriter out = new BufferedWriter(writing);
out.write(t)
out.close();
...
if I write sometring into the file, then it goes to the first line. But if run the programm again, it writes the new text over the previous text (into the first line). I want to do: if I insert something, then it goes to the next line. For example:
after 1 input) text1
after 2 input) text1
text2
and so on...
what should i change in the code?
thanks!
java.io.PrintWriter pw = new PrintWriter(new FileWriter(fail, true));
This should do it. Use that over the existing pw line.
edit: And as explained in the comments, this is causing the following things to happen:
A FileWriter is being created, with the optional 'append' flag being set to true. This causes FileWriter to not overwrite the file, but open it for append and move the pointer to the end of the file.
PrintWriter is using this FileWriter (as opposed to creating its own with the file you pass it.)
(A lot of editing going on here. I was uncertain about the question a few times.)
I suggest you use the append flag in the FileWriter constructor.
You also might line to add a newline between each write ;)
why dont you use RandomAccessFile?
In RandomAccessFile, read/write operations can be performed at any position.The file pointer can be moved to anyplace by seek() method. You have to specify file opening mode while using it.
Example:
RandomAccessFile raf = new RandomAccessFile("anyfile.txt","rw"); // r for read and rw for read and write.
and to take the file pointer to EOF you have to use seek().
raf.seek(raf.length());
Instead of using BufferedWriter, use
PrintWriter out = new PrintWriter(kirjutamine);
out.print(t);
out.close();