PrintWriter overwrite data [duplicate] - java

This question already has answers here:
Is this the best way to rewrite the content of a file in Java?
(8 answers)
Closed 7 years ago.
I'm trying to keep track of a high score in a game I'm making by doing:
PrintWriter out = new PrintWriter(new File("path"));
while(gameLoop) {
out.write(highScore);
out.flush();
}
It keeps appending the data to the end of the file. I am aware I could out.close(); and then out = new PrintWriter(new File("path")); but that seems like a lot of excess code. Constantly closing and re-opening the file to achieve overwrite. Is there any way for my PrintWriter to overwrite the data without closing and re-opening the file?

First, I would suggest you use print (or println) with a PrintWriter. Next, if I understand your question, you could use a try-with-resources Statement and something like
while (gameLoop) {
try (PrintWriter out = new PrintWriter(new File("path"))) {
out.println(highScore);
}
}
which will close and re-open the PrintWriter on every iteration of the loop. Alternatively, you could use nio and something like
Path file = Paths.get("path");
while (gameLoop) {
byte[] buf = String.valueOf(highScore).getBytes();
Files.write(file, buf);
}

Related

Java how to add new line to file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 2 years ago.
Im trying to add multiple strings to a file.
FileWriter myWriter = new FileWriter("cache.txt");
BufferedWriter bw=new BufferedWriter(myWriter);
bw.write(marker);
bw.newLine();
bw.close();
But whenever I write a new String it keeps overriding.
So I only have one string in my file.
How would I make it add a new line to the file.
Here is an example
What should happen.
file(cache.txt):
fd174d5b4bbc85295a649f9d70a4adf4
9b854017b04d62732ac00f2ee8007968
...
What happens for me
file(cache.txt):
9b854017b04d62732ac00f2ee8007968(last entry)
Because that's what BufferedWriter's .write is supposed to do.
If the file doesn't exists, create and write to it.
If the file exists, truncate (remove all content) and write to it
To append, use this:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("text");
out.close();
} catch (IOException e) {
//exception handling
}
Use the "append" flag to the FileWriter constructor:
FileWriter myWriter = new FileWriter("cache.txt", true);
Otherwise the file will be reset to the beginning each time it is opened.

Writing File in java with Array List but not working [duplicate]

This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 4 years ago.
It seems fine but the the content is not write into file with write() method. I ask the user input with JoptionPane and add that data to ArrayList . The data is added , but when I try to output that data into file, it's not write to file.
public class fileArray {
public static void main(String[] args) throws IOException {
ArrayList al = new ArrayList();
File f =new File("notworking.txt");
String names = " ";
while(!names.isEmpty())
{
names=JOptionPane.showInputDialog("EnterName");
if(!names.isEmpty()){
al.add(names);}
}
FileWriter fw = new FileWriter(f.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
int sz= al.size();
for(int i =0;i<sz;i++){
bw.write((String) al.get(i));
System.out.println(al.get(i));
}
}
}
You need to close the writer after you are done with writing.
bw.close();
Either you have to flush or close the buffer afte you write to the file. Better you close the buffer in finally block, make it habit to close the buffer in finally block.
sample code:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close(); // CLOSE

Java FileWriter lost special characters [duplicate]

This question already has answers here:
Java BufferedWriter object with utf-8
(4 answers)
Closed 7 years ago.
I've this code
//write a file in a specific directory
public static void writeFile(String comment, String outputFileName) {
FileWriter fWriter = null;
BufferedWriter writer = null;
try {
fWriter = new FileWriter(outputFileName,true);
writer = new BufferedWriter(fWriter);
writer.write(comment);
writer.newLine();
writer.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
But when I save the file in outputFileName, it lost every special character.
File output format is .txt
Some solution?
Thanks a lot
FileWriter uses the platform-default encoding. It's very rarely a good idea to use that class, IMO.
I would suggest you use an OutputStreamWriter specifying the encoding you want - where UTF-8 is almost always a good choice, when you have a choice.
If you're using Java 7 or higher, Files.newBufferedWriter is your friend - and with Java 8, there's an overload without a Charset parameter, in which case UTF-8 is used automatically.

Printwriter how not to overwrite [duplicate]

This question already has answers here:
PrintWriter append method not appending
(5 answers)
Closed 9 years ago.
So I got this piece of code in my Java program;
String filename = "direct.txt";
String s = fil.getAbsolutePath();
Process p = Runtime.getRuntime().exec(s);
try
{
PrintWriter outputStream = new PrintWriter(filename);
outputStream.println(s);
outputStream.close();
}
catch (FileNotFoundException e1) {e1.printStackTrace();};
But when it writes to the file, it overwrites it when it writes something new, how can I make it so it doesn't overwrite but instead goes to the next line and prints it there?
You could make a FileWriter object and pass it as an argument when making the PrintWriter object. That way if the file already exists then it won't be overwritten, but if it does not exist then it will be created. From there you can use the PrintWriter methods as normal:
FileWriter objectName = new FileWriter("filename", true);
PrintWriter outputStream = new PrintWriter(objectName);

JAVA: IO Exception: Reason Stream closed

Why am I getting the following exception? What I am doing is writing a giant ArrayList line by line to a file onto the disk. The file generated is about >700MB.
It seems like it has some problem when written line by line. Could the size of the file a reason? Why is the stream closed? By the way, I am working on a Windows OS.
FileWriter evaluated_result =
new FileWriter(path_output+this.algorithm+"/"+query_type+"/"+"queries.eval");
BufferedWriter out = new BufferedWriter(evaluated_result);
out.write(Myobject);
out.newLine();
evaluated_result.close();
out.close();
The exception is as follows:
java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:45)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:118)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)
at java.io.BufferedWriter.close(BufferedWriter.java:264)
at Assignment_1.Query_Evaluator.write100BestDocumentsEvalFormat(Query_Evaluator.java:85)
at Assignment_1.Experiment.ConductExperiment(Experiment.java:54)
at Assignment_1.Main.main(Main.java:78)
You should close the BufferedWriter before closing the FileWriter.
And, the closing calls should be in a finally block. This is one way to do it (with one finally):
FileWriter evaluated_result = new FileWriter(path_output+this.algorithm+"/"+query_type+"/"+"queries.eval");
BufferedWriter out = new BufferedWriter(evaluated_result);
try {
out.write(Myobject);
out.newLine();
}
finally {
if (out != null) out.close();
if (evaluated_result != null) evaluated_result.close();
}
(Look here for more options)
Also note that, as mentioned by #oldrinb, you don't have to close nested streams. But I think it's good practice anyway.
With Java 7 you can use the try-with-resources statement.

Categories

Resources