有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

为什么我不能用java读取文件的所有行?

我试图用Java制作一个文本编辑器,但我似乎无法让“打开文件”功能正常工作。当我运行代码时,它只显示文件的第一行。我已经尝试了:How to read a large text file line by line using Java?中的所有代码片段,但它仍然只读取第一行

这就是我尝试过的:

            JMenuItem mntmOpen = new JMenuItem("Open");
            mntmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
            mntmOpen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            if (e.getSource() == mntmOpen) {
                int returnVal = fc.showOpenDialog(null);

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    //This is where a real application would open the file.

                    Path HI = file.toPath();


                    try( Stream<String> lines = Files.lines(HI)
                            ){
                        for( String line : (Iterable<String>) lines::iterator )
                        {
                            editorPane.setText(line); 
                        } 
                    }catch (IOException e1) {

                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }


                }
            }
        }
    });

共 (1) 个答案

  1. # 1 楼答案

    在这里查看这个答案,您应该能够使用while循环中的部分。非常直接地运行直到null,这基本上表示缓冲区将继续读取,直到读取器发回null指针,在这种情况下,文件中没有任何内容。如果这不起作用,我们可以再看一次。此外,如果你问了一个问题而没有先寻找答案,你也会被否决https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html