繁体   English   中英

扫描仪警告:资源泄漏: <unassigned closeble value>

[英]Scanner warning: Resource leak : <unassigned closeble value>

我正在读取文件并将其内容存储在字符串中。 该代码给我警告: 资源泄漏: 我该如何解决?

public static String JsonFileToString(String FileName)
{
    String FileContent=null;
    try {

        FileContent = new Scanner(new File("src/main/resources/" + FileName)).useDelimiter("\\Z").next();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }


    return FileContent;

}

您必须将Scanner分配给变量,以便可以在finally块中将其关闭。

String FileContent=null;
        Scanner sc = null;
        try {

            sc = new Scanner(new File("src/main/resources/" + ""));
            FileContent = sc.useDelimiter("\\Z").next();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            sc.close();
        }

您没有关闭为读取文件而创建的Scanner ,因此此后文件仍保持打开状态。

假设您使用的是Java 7+,请使用try-with-resources确保清除了扫描程序:

try (Scanner sc = new Scanner(new File("src/main/resources/" + FileName)).useDelimiter("\\Z")) {
  return sc.next();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM