我想将 String
写入 Unicode 文件。我在 Java
中的代码是:
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;
}
更新
现在将它与 C# 进行比较:
private static bool SaveStringToFile(string fileName, string text)
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.Write(text);
}
}
甚至 try..catch
形式将是:
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();
}
}
也许是因为我来自 C# 和 .Net 世界。但这是将字符串写入文件的正确方法吗?对于这样简单的任务来说,代码太多了。在 C# 中,我会说只是 out.close();
就是这样,但是在 中添加
语句。无论发生什么,我都添加了 try..catch
似乎有点奇怪finallyfinally
语句来关闭文件(资源)。避免使用过多的资源。这是Java中的正确方法吗?如果是这样,为什么 close
会抛出异常?
最佳答案
你是正确的,你需要在 finally block 中调用 close() 并且你还需要包装这是一个 try/catch
通常你会在你的项目中编写一个实用方法或使用库中的实用方法,如 http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly(java.io.Closeable)安静地关闭。即忽略 close() 中的任何抛出异常。
另外说明,Java 7 增加了对资源尝试的支持,无需手动关闭资源 - http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
关于c# - 尝试...在释放资源时最终捕获内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14156132/