尝试。。。释放资源时终于在里面抓了?
2022-09-02 04:15:34
我想将 一个写入 Unicode 文件。我的代码是:String
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#中,我会说只是,就是这样,但是在语句中添加一个似乎有点奇怪。我添加了该语句以关闭文件(资源),无论发生什么情况。避免使用过多资源。这在Java中是正确的方式吗?如果是这样,为什么会引发异常?out.close();
try..catch
finally
finally
close