它说进程已完成但没有输出

问题描述 投票:0回答:2

我是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();
    }
}
java process
2个回答
0
投票

您忽略了异常并且没有关闭文件。通过使用内置

input.transferTo()
将文件复制到
System.out
来节省一些输入,并通过将
throws IOException
添加到构造函数和
main
来传递异常以供调用者处理。

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

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

编辑

您可以用

Files.copy
提供的一行替换上面的内容:

Files.copy(path, System.out);

-1
投票

您成功调用了预期的类,但您还需要指定在函数中声明的特定函数。就像这样:

public static void main (String[] args) { GuessingGame gg = new GuessingGame; gg.GuessingGame(); }

© www.soinside.com 2019 - 2024. All rights reserved.