java - while block 中的初始化?

标签 java

是否有更简洁的方法来执行以下操作(消除在 while block 之前初始化行的需要)?似乎没有必要在使用变量之前对其进行初始化,而不是执行类似 while ((String line = br.readLine) != null) {} 之类的操作。如果没有,为什么不呢?

BufferedReader reader = null;

try
{
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null)
    {
        System.out.println(line);
    }

}
catch (IOException e)
{
    e.printStackTrace();
}
finally
{
    try
    {
        reader.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

最佳答案

不,您无法避免初始化变量。但是,您可以使用 Try-With-Resources让它变得更干净。

try (BufferedReader reader = new BufferedReader(new FileReader("sample-file.dat"))) {
    String line;  
    while ((line = reader.readLine()) != null)
    {
        System.out.println(line);
    }
}
catch (IOException e)
{
    e.printStackTrace();
}

关于java - while block 中的初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26383865/

相关文章:

java - 致命异常/无法在 Android 中实例化错误

java - 如何在wave文件编辑器中面对java堆内存不足错误

java - 代码中是否发生了线程饥饿死锁?

java - 如何RSA验证在php中生成的java中的签名

Java LED 编程

java - 使用 super 关键字迭代通用列表

java - 有没有办法使用 maven 指定要包含在 EAR 中的 data-sources.xml 文件?

java - 使用语音进行生物识别 - Android

java - 在java中模拟调用外部方法

Java 11 + Chrome/Firefox = TLS 解密错误