[英]Java Scoping & Visibility Rules
经过一段漫长的时间后,我重新回到用Java编写代码-过去几年中我的大部分编码工作都在PHP和JavaScript中进行-并且发现我必须更加努力地满足Java编译器的要求,而该编译器要严格得多关于变量范围和异常处理等问题。 导致我有些麻烦的一段代码如下所示
File file = new File(path, fname);
FileOutputStream stream = null;
try
{
stream = new FileOutputStream(file);
stream.write(tosave.getBytes());
}
finally
{
try
{
if (null != stream) {stream.close();}
return true;
}
catch(Exception e){return false;}
}
这被编译器接受。 但是,在我到达这里之前,我遇到了几个问题。
stream
内的可变try
块。 编译器再次出现抖动- stream
变量在finally
块中超出范围。 如您所见,我通过在try
块上方声明stream
并将其初始化为null来解决此问题。
这可行。 但是,考虑到我的Java技能多么生锈,我想问一下:是否有编写这种代码的正确方法 ?
在现代Java版本(自Java 7起)中,处理此类情况的惯用方式是使用try-with-resource块,该块为您处理所有难看的“逻辑”。 您仍然必须捕获异常或向上传播该异常,但这是一个相对较小的问题。 考虑以下:
public static boolean writeToFile(String path, String fname) {
File file = new File(path, fname);
try (FileOutputStream stream = new FileOutputStream(file)) {
stream.write(tosave.getBytes());
} catch (IOException e) {
// Should probably log the exception too
return false;
}
return true;
}
您可以简单地使用以下代码片段:
try (FileOutputStream stream = new FileOutputStream(file)){
stream.write(tosave.getBytes());
}catch(IOException e) {
e.printStackTrace();
return false;
}
return true;
这是Java 7中引入的一项新功能( try-with-resources语句 )。
我认为您已经迷上了不重要的东西。 是的,在某些情况下,对try / catch / finally进行编码非常重要,因为您实际上需要采取一些措施来纠正错误。
但是对于打开/关闭文件,您并不想为了满足编译器而陷入困境。 代码的可读性更为重要。
怎么样:
String path="somepath";
String fname="somefile";
String tosave="somedata";
try {
File file = new File(path, fname);
FileOutputStream stream = new FileOutputStream(file);
stream.write(tosave.getBytes());
stream.close();
}
catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.