我想将 a 写入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();
添加一个似乎有点奇怪。无论发生什么,我都添加了关闭文件(资源)的语句。避免使用过多的资源。这是Java中的正确方法吗?如果是这样,为什么会抛出异常?try..catch
finally
finally
close