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.
Related
I'm writing code to read a file and process it and I'm splitting logic into many small methods. So I have a method to read the file and return BufferedReader and another one to do logic with the returned BufferedReader object. But when I try to read lines from the BufferedReader object in the second method it gives me [java.io.IOException: Stream Closed].
The method I used to read the file and return BufferedReader
private static BufferedReader readFile(String file) {
try (FileInputStream fileInputStream = new FileInputStream(file)) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
System.out.println(bufferedReader.readLine()); // this line is working successfully
return bufferedReader;
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Any idea why the happens and how to solve it ?
You are using try-with-resources:
try (FileInputStream fileInputStream = new FileInputStream(file)) {
This line is creating a FileInputStream which can be used inside your try block. As soon as you leave your try block, the close() method will be called onto the stream. So if you return the stream or its BufferedReader, the stream will already be closed. You should not use try-with-resources or even better, return whatever you need from the stream instead of the stream itself.
Obviously, the problem here lies in the use of try-with-resources, and AutoCloseable interface. However, i would like to point out that the way you read the file is the "old fashioned" way. We now have the Files, Paths, and Stream classes to facilitate reading of files. this uses java NIO, returns a Stream and is better overall:
Files.lines(Paths.get(pathToFile))
additionally, nothing has to be closed here
What is wrong in the below code? in console it is printing proper data but in file there is no data. it is creating 0-byte file.
JsonObjectBuilder mainObj= Json.createObjectBuilder();
mainObj.add("delete",delete);
mainObj.add("update", update);
mainObj.add("add",add);
String data = mainObj.build().toString();
System.out.println(data); **//This line printing output**
BufferedWriter out = new BufferedWriter(new FileWriter("D:/test.json"));
out.write(data);
Below output is getting printed to console but it is creating 0-byte file.
{"delete":[{"canonicalName":"Amazon"}],"update":[{"canonicalName":"Infosys"},{"canonicalName":"Google HYD"}],"add":[{"canonicalName":"Apple computers"},{"canonicalName":"Microsoft India"},{"canonicalName":"Amazon"},{"canonicalName":"Google India"},{"canonicalName":"CSC"},{"canonicalName":"INFY"}]}
As mentioned in the comments you forgot to close the writer.
Instead of out.close() you can also use the new syntax try-with-resources since Java 7:
try (BufferedWriter out = new BufferedWriter(new FileWriter("D:/test.json"))) {
out.write(data);
}
This will automatically close all Closeables at the end of the try block.
Attention: the FileWriter will not be closed by the try-with-resource mechanism as there is no variable created for the FileWriter. Luckily the BufferedWriter.close() will also close the passed FileWriter.
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);
}
This question already has answers here:
How can I download and save a file from the Internet using Java?
(23 answers)
Closed 7 years ago.
I am reading the contents of a URL and write a file the problem is that I'm not able to write all the content in the file and do not know what I'm doing wrong.
My code,
try {
URL url = new URL(sourceUri);
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
file.getParentFile().mkdirs();
file.createNewFile();
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
while ((inputLine = br.readLine()) != null) {
bw.write(inputLine + System.getProperty("line.separator"));
}
br.close();
System.out.println("DONE");
}catch (IOException ioe){
ioe.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
return ontologies;
}
Please help
You are doing many things incorrectly.
First: you don't close all your resources; where is the writer to the file closed?
Second: you use new InputStreamReader(...) without specifying the encoding. What says that the encoding on the other end is the one of your JVM/OS combination?
Last but not least, and in fact, this is the most important, you should use java.nio.file. This is 2015 after all.
Simple solution:
final Path path = file.toPath(); // or rather use Path directly
Files.createDirectories(path.getParent());
try (
final InputStream in = conn.getInputStream();
) {
Files.copy(in, path);
}
Done, encoding independent, and all resources closed.
The problem is you're using a BufferedWriter and you don't close it. It has some content in his buffer that is not writing and you're missing.
Try flushing the buffer and closing the BufferedWriter:
bw.flush();
bw.close();
Include this two lines after before your br.close();.
Also you can read how BufferedWriter works here.
And I think you should close FileWriter, too, in order to unblock the file.
fw.close();
EDIT 1:
Closing the BufferedWriter will flush the buffer for you. You need only to close it.
I am trying an example from
http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
in the example the BufferReader is not closed is that necessary to close the BufferReaderor not? Please explain.
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
Always close streams. It's a good habit which helps you to avoid some odd behaviour. Calling close() method also calls flush() so you don't have do this manually.
The best place where to close streams is probably in a finally block. If you have it like in your example and an exception occurs before the in.close() line, the stream won't be closed.
And if you have chained streams, you can only close the last one and all before it are closed too. This means br.close() in your example - not in.close();
Example
try {
// do something with streams
} catch (IOException e) {
// process exception - log, wrap into your runtime, whatever you want to...
} finally {
try {
stream.close();
} catch (IOException e) {
// error - log it at least
}
}
Alternatively you can use closeQuietly(java.io.InputStream) in Apache Commons library.
From the perspective of resource leak prevention, it is not strictly necessary to close a wrapper stream if you've also closed the stream that it wraps. However, closing the wrapped stream may result in stuff getting lost (specifically in the output case), so it is better to close (just) the wrapper, and rely on documented behavior that the closing the wrapper closes the wrapped stream too. (That is certainly true for the standard I/O wrapper classes!)
Like Peter Lawrey, I question the wisdom of relying on "Rose India" examples. For instance, this one has two more obvious mistakes in it that no half-decent Java programmer should make:
The stream is not closed in a finally block. If any exception is thrown between opening and closing, the in.close() statement won't be executed, and the application will leak an open file descriptor. Do that too often and your application will start throwing unexpected IOExceptions.
The DataInputStream in the chain serves no useful purpose. Instead, they should use fstream as the parameter for the InputStreamReader. Or better still, use FileReader.
Finally, here is a corrected version of the example:
BufferedReader br = new BufferedReader(new FileReader ("textfile.txt"));
try {
String line;
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println(line);
}
} finally {
// Close the reader stack.
br.close();
}
or using Java 7's "try with resource":
try (BufferedReader br = new BufferedReader(new FileReader ("textfile.txt"))) {
String line;
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println(line);
}
}
Since the underlying stream is closed, it is not absolutely necessary to close BufferedReader, even though it is a good practice to close ALL Closeables in reverse order (relative to the order they were opened in.)