I want to write a String
to a Unicode file. My code in Java
is:
public static boolean saveStringToFile(String fileName, String text) {
BufferedWriter out = null;
boolean result = true;
try {
File f = new File(fileName);
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(f), "UTF-8"));
out.write(text);
out.flush();
} catch (Exception ex) {
result = false;
} finally {
if (out != null)
try {
out.close();
} catch (IOException e) {
// nothing to do! couldn't close
}
}
return result;
}
Now compare it to C#:
private static bool SaveStringToFile(string fileName, string text)
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.Write(text);
}
}
or even try..catch
form would be:
private static bool SaveStringToFile(string fileName, string text)
{
StreamWriter writer = new StreamWriter(fileName);
try
{
writer.Write(text);
}catch (Exception ex)
{
return false;
}
finally
{
if (writer != null)
writer.Dispose();
}
}
Maybe it's because I'm from the C# and .Net world. But is this the right way to write a String to a file? It's just too much code for such simple task. In C#, I would say to just out.close();
and that was it but it seems a bit strange to add a try..catch
inside a finally
statement. I added the finally
statement to close the file (resource) no matter what happens. To avoid using too much resource. Is this the right way in Java? If so, why close
throws exception?
A try-finally block is possible without catch block. Which means a try block can be used with finally without having a catch block.
No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.
The finally-block The finally block contains statements to execute after the try block and catch block(s) execute, but before the statements following the try... catch... finally block.
You are correct in that you need to call the close() in the finally block and you also need to wrap this is a try/catch
Generally you will write a utility method in you project or use a utility method from a library like http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly(java.io.Closeable) to closeQuietly .i.e. ignore any throw exception from the close().
On an additional note Java 7 has added support for try with resources which removes the need to manually close the resouce - http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Yes, There is nothing strange about Try catch inside finally() in java. close() may throw IoException for various reasons, thats why it has to enclosed by try catch blocks. There is an improved solution to this problem of yours, in the latest java SE 7 Try with resources
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With