Ali*_*ori 21 c# java programming-languages
我想写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;
}
Run Code Online (Sandbox Code Playgroud)
现在将它与C#进行比较:
private static bool SaveStringToFile(string fileName, string text)
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.Write(text);
}
}
Run Code Online (Sandbox Code Playgroud)
甚至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();
}
}
Run Code Online (Sandbox Code Playgroud)
也许是因为我来自C#和.Net世界.但这是将String写入文件的正确方法吗?这个简单的任务代码太多了.在C#中,我会说,就是out.close();这样,但try..catch在finally声明中添加一个内容似乎有点奇怪.我添加了finally语句来关闭文件(资源),无论发生什么.避免使用太多资源.这是Java中的正确方法吗?如果是这样,为什么close抛出异常?
bst*_*k12 17
你是正确的,你需要调用finally块中的close(),你还需要包装这是一个try/catch
通常,您将在项目中编写实用程序方法,或者使用http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly(java.io)等库中的实用程序方法..Closeable)关闭.ie忽略close()中的任何抛出异常.
另外需要注意的是,Java 7增加了对try资源的支持,无需手动关闭资源 - http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
| 归档时间: |
|
| 查看次数: |
2430 次 |
| 最近记录: |