here is the code.
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
fis = new FileInputStream(new File("D:\\za180s.ser"));
// do something
fis = new FileInputStream(new File("D:\\za185s.ser"));
// do something
fis = new FileInputStream(new File("D:\\za186s.ser"));
// do something
fis = new FileInputStream(new File("D:\\za187s.ser"));
// do something
fis.close();
}
the problem is : need i call fis.close() method after every "do something" or i just call fis.close() once after all.
ignore whether the close() position in finally and the code need try catch or not.
thx all.
Yes, you need to call close on each individual InputStream. The problem with your code is that you're reassigning the variable fis each time you create a new stream. In other words: fis no longer points to the old InputStream, so calling close will not close the previous stream.
For more information, check https://stackoverflow.com/a/40523/8819761
What you could also do is use Java 7's try-with-resources syntax, which will auto-close the stream once you exit the try block:
try (InputStream fis = new FileInputSteam(yourFile)) {
// Do something
}
try (InputStream fis = new FileInputSteam(yourFile)) {
// Do something else
}
You have to do close everytime you finish working with InputStream.
In java, if you assign
fis = new FileInputStream(new File("D:\\za180s.ser"));
fis will point to the new object so when you call fis.close() the old streams are not affected. And there is no way to close it.
You need to call close method every time but don't worry now.From Java SE 7 you can use try-with-resources. As per Java-Oracle Doc,
The try-with-resources statement is a try statement that declares one
or more resources. A resource is an object that must be closed after
the program is finished with it. The try-with-resources statement
ensures that each resource is closed at the end of the statement. Any
object that implements java.lang.AutoCloseable, which includes all
objects which implement java.io.Closeable, can be used as a resource.
Please have a look on example.
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
For more details, Please have a look on Oracle-Java doc for try-with-resources.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Related
Earlier the code was like this -
try {
some other code
......
......
ByteArrayInputStream annoBais = new ByteArrayInputStream(annoBytes);
DataInputStream dis = new DataInputStream(annoBais);
InputStream annoStream = dis;
inputRecord.put("XMLStream", annoStream);
MappedRecord resultMappedRecord = (MappedRecord)interaction.execute(interactionSpec,inputRecord);
HashMap mappedAnnotIds = (HashMap)resultMappedRecord.get(("ResultHashMap").toString());
annoStream.close(); //closed here
annoBais.close(); // closed here
dis.close(); // closed here
......
......
some more code
}
I changed it to -
try {
some other code
......
......
#lombok.Cleanup ByteArrayInputStream annoBais = new ByteArrayInputStream(annoBytes);
#lombok.Cleanup DataInputStream dis = new DataInputStream(annoBais);
#lombok.Cleanup InputStream annoStream = dis;
inputRecord.put("XMLStream", annoStream);
MappedRecord resultMappedRecord (MappedRecord)interaction.execute(interactionSpec,inputRecord);
HashMap mappedAnnotIds = (HashMap)resultMappedRecord.get(("ResultHashMap").toString());
......
......
some more code
}
Is #lombok.Cleanup going to have the same scope ? Will it close at the same place where it was earlier being closed manually ? If not, how can I close it in a way that it still has the same scope ?
The correct way to use #lombok.Cleanup here is by not using lombok; Java7 solves this with try with resources.
Eg, with your code:
some other code
......
......
try ( ByteArrayInputStream annoBais = new ByteArrayInputStream(annoBytes);
DataInputStream dis = new DataInputStream(annoBais) ) {
InputStream annoStream = dis;
inputRecord.put("XMLStream", annoStream);
MappedRecord resultMappedRecord = (MappedRecord)interaction.execute(interactionSpec,inputRecord);
HashMap mappedAnnotIds = (HashMap)resultMappedRecord.get(("ResultHashMap").toString());
}
// annoBais & dis get closed here.
// Note: annoStream is an alias of dis, not a separate resource.
......
......
some more code
Of course, this code needs to be surrounded by a try {} catch () {} block, or your method must declare that it throws the required exceptions.
Using "try with resources" does not cause you to have to handle additional exceptions. You always need to handle all checked exceptions, either by catching them or declaring your methods throws them.
With
#lombok.Cleanup ByteArrayInputStream annoBais = new ByteArrayInputStream(annoBytes);
#lombok.Cleanup DataInputStream dis = new DataInputStream(annoBais);
#lombok.Cleanup InputStream annoStream = dis;
all three resources get closed at the closing brace in reverse order of their declaration. AFAIK, that's exactly the same as with try-with-resources.
#Cleanup works even when some of the close statement throw. That's the same, too.
It works even with Java 6, but you really shouldn't be using Java 6.
#Cleanup has a superior syntax, but that's subjective. I'm stopping using it as try-with-resources is a build-in feature sure to be supported forever or alike.
Also using try with resources is causing me to handle few other exceptions.
Definitely not, this must be the same, too. Note that 99% of the time, you should add the exceptions to the throws clause or wrap and re-throw them.
Note that
#lombok.Cleanup InputStream annoStream = dis;
makes no sense as you're not acquiring a new resource. So
InputStream annoStream = dis;
would be better as there's nothing new to close. Even better would be to ditch annoStream as it hardly ever makes sense to have two variables for one thing.
Luckily, calling close multiple times is harmless.
This question already has answers here:
Correct way to close nested streams and writers in Java [duplicate]
(10 answers)
Closed 6 years ago.
When using a PrintWriter like this :
PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter(csvFileIn)));
What do I need to close in the finally block ? The PrintWriter, the BufferedWriter and the FileWriter ?
Do I need to try catch the close statement in the finally block ?
[EDIT]
I need to use java 6, so I can't use the try-with-resources statement.
You can use a try-with-resources block
try (PrintWriter fileOut = new PrintWriter(new BufferedWriter(new FileWriter(csvFileIn)))) {
//WHATEVER you need to do
}
Since PrintWriter implements AutoCloseable it will close by itself once the try block is complete (even if an exception is raised)
Check more info about this here
You should use -
fileOut.close();
As you do not have any variable name assigned to BufferedWriter or FileWriter also the fileOut is made from them when you close fileOut it will in turn close both the streams.
Strictly speaking, you should close all three streams. And I would even add a fourth layer, since you probably don’t want to write out the CSV file using the default system encoding, but a customer-specified one. So this is it:
try (FileOutputStream fos = new FileOutputStream(csvFileIn);
FileWriter fwr = new FileWriter(fos, StandardEncodings.UTF_8);
BufferedWriter bwr = new BufferedWriter(fwr);
PrintWriter pwr = new PrintWriter(bwr)) {
pwr.println("Field1;Field2;Field3");
pwr.println("Data1;Data2;Data3");
}
In practice, usually only the outermost stream is closed, since it (usually) forwards the close() call to its wrapped stream, and getting an OutOfMemoryError between opening the file and reaching the try block is very unlikely. Then, it looks like this:
try (PrintWriter pwr = new PrintWriter(new BufferedWriter(new FileWriter(new FileOutputStream(csvFileIn), StandardEncodings.UTF_8)))) {
pwr.println("Field1;Field2;Field3");
pwr.println("Data1;Data2;Data3");
}
As per as my knowledge we use try catch as follows:
try {
//Some code that may generate exception
}
catch(Exception ex) {
}
//handle exception
finally {
//close any open resources etc.
}
But in a code I found following
try(
ByteArrayOutputStream byteArrayStreamResponse = new ByteArrayOutputStream();
HSLFSlideShow pptSlideShow = new HSLFSlideShow(
new HSLFSlideShowImpl(
Thread.currentThread().getContextClassLoader()
.getResourceAsStream(Constants.PPT_TEMPLATE_FILE_NAME)
));
){
}
catch (Exception ex) {
//handel exception
}
finally {
//close any open resource
}
I am not able to understand why this parentheses () just after try.
What is the usage of it? Is it new in Java 1.7? What kind of syntax I can write there?
Please also refer me some API documents.
It is try with Resources syntax which is new in java 1.7. It is used to declare all resources which can be closed. Here is the link to official documentation.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
This question already has answers here:
Try With Resources vs Try-Catch [duplicate]
(5 answers)
Closed 7 years ago.
Working with objects we use 3 basic steps:
Declaration
Instantiation
Initialization
And my question is about what steps must be done in () part of try-with in order auto close on resource to be made.
Example 1 - will FileReader object be auto closed in this code:
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
//some code;
}
Example 2 - will the buf2 be auto closed in this code:
private static BufferedReader buf1;
public static void main(String[] args) throws IOException {
//some code
try (BufferedReader buf2 = buf1)
{
}
}
P.S. Someone supposes that this question is duplicate of Try With Resources vs Try-Catch . It is not. That question is about difference between try-catch and try-with-resources. My question is about details of try-with.
Whenever language related details are needed, the most complete reference is the Java Language Specification (just Google it). For the try-with-resources statement, you can read section 14.20.3 which states that the following:
try ({VariableModifier} R Identifier = Expression ...)
Block
is translated to
{
final {VariableModifierNoFinal} R Identifier = Expression;
Throwable #primaryExc = null;
try ResourceSpecification_tail
Block catch (Throwable #t) {
#primaryExc = #t;
throw #t;
} finally {
if (Identifier != null) {
if (#primaryExc != null) {
try {
Identifier.close();
} catch (Throwable #suppressedExc) {
#primaryExc.addSuppressed(#suppressedExc);
}
} else {
Identifier.close();
}
}
}
}
In your first example, the resource R is BufferedReader, the Identifier is br and the Expression is new BufferedReader(new FileReader(filePath)). It follows that only the BufferedReader is closed in the implicit finally block. The finally block will not call close on the FileReader because it is not part of the resource declaration itself. However, it happens that the implementation of BufferedReader.close() internally calls the close method of the wrapped FileReader. So the answer to the first question is yes simply because the wrapper object closed it (following the common wisdom that a resource should release any wrapped resource when being itself released), not because of the try-with-resources.
In the second example:
private static BufferedReader buf1;
public static void main(String[] args) throws IOException {
//some code
try (BufferedReader buf2 = buf1)
{
}
}
the answer depends on the some code. Here buf2 and buf1 both refer to the same object in memory. If this "some code" initializes buf1 to some object, then this object will be closed since buf2 also refers to it. If not and buf1 is null (and therefore buf2 is null), then nothing will be closed because of the null check in the implicit finally shown above.
FileReader will be closed. But that is not because it is in the try statement. It is because when BufferedReader is closed, it calls close() on FileReader as well. For a counter example, I have a class called X that implements AutoCloseable. And that class needs a Foo object in its constructor. So I write:
try (X x = new X(new Foo())) {
}
Will Foo be closed? It doesn't even implement AutoCloseable!
I wrote the following to test this:
BufferedReader buf1 = null;
try (BufferedReader buf2 = buf1) {
}
And it worked perfectly fine, no exceptions! My guess is that at the end of the try statement, it checks whether the object is null. If it is not, then close it. So in this case, because buf2 is null, it can't be closed.
I'am trying to write the inputstream image to OutputStream to display the image in the browser this is the code:
try
{
InputStream input = Filer.readImage("images/test.jpg");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1)
{
responseBody.write(buffer, 0, bytesRead);
}
}
catch(IOException e)
{
System.out.println(e);
}
the readImage:
public static InputStream readImage(String file) throws IOException {
try (InputStream input = new FileInputStream(file)) {
return input;
}
}
but I get an error while writing:
java.io.IOException: Stream Closed
any ideas?
The try-with-resources closes the stream when you exit the block
try (InputStream input = new FileInputStream(file)) {
ie. when your method returns.
Just remove it and take care of closing the stream at the end of your other method body.
As stated in the comments, here's a link to the official tutorial on try-with-resources.
Taken from oracle tutorial the resource is closed when the statement completes:
The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement: