首页 > 解决方案 > 它说 Process Finished 但没有输出

问题描述

我是 java 新手,我的代码有点问题。没有错误等,它只是一直说进程完成但没有显示输出。我检查过的文件名是正确的。

导入 java.nio.file。; 导入 java.io。;

public class GuessingGame {
    public GuessingGame() {
        String filename = "C:\\Users\\angela\\Documents\\words.txt";
        Path path = Paths.get(filename.toString());
        
        try {
            InputStream input = Files.newInputStream(path);
            BufferedReader read = new BufferedReader(new InputStreamReader(input));
            
            String word = null;
            while((word = read.readLine()) !=null) {
                System.out.println(word);
            }
        }
        catch(IOException ex) {
            
        }
    }
    public static void main (String[] args) {
        new GuessingGame();
    }
}

标签: javaprocess

解决方案


您忽略了异常并且没有关闭文件。通过使用内置的input.transferTo()将文件复制到保存一些输入,并通过添加到构造函数和System.out传递异常给调用者处理。throws IOExceptionmain

用这个 try-with-resources 替换你的 try-catch 块,它处理使用后关闭文件:

try (InputStream input = Files.newInputStream(path)) {
    input.transferTo(System.out) ;
}

推荐阅读