-5

I'm trying to make a text editor in Java, but I can't seem to get the "open file" feature to work. When I run the code, it only displays the first line of a file. I've tried all of the code snippets from: How to read a large text file line by line using Java?, but it still reads the first line only.

This is what I have tried:

            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();
                        }


                }
            }
        }
    });
Community
  • 1
  • 1
GreenJames
  • 21
  • 1
  • 8
  • 1
    Show what you have tried. – Luke Joshua Park Apr 24 '16 at 02:26
  • 2
    *"but it still reads the first line only."* Your code doesn't do that. Create a [mcve], please. – Tom Apr 24 '16 at 02:36
  • Perhaps you need a StringBuilder and put some new lines into your output? – OneCricketeer Apr 24 '16 at 02:37
  • Btw: the easiest way to read all lines of the file is [`Files#readAllLines`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllLines-java.nio.file.Path-). – Tom Apr 24 '16 at 02:38
  • 2
    Wow. First: your posted way of reading lines has _nothing_ to do with the ways you've posted before. And secondly: `editorPane.setText(line);` do you think that this _appends_ the read line? Have you checked the JavaDoc about this? – Tom Apr 24 '16 at 02:42

1 Answers1

0

Check out this answer here, you should be able to use the section in the while loop. Pretty straight forward run until null which basically states that the buffer will continue to read until the reader sends back a null pointer in which case there is nothing left in the file. If this doesn't work then we can take a look at it again. Also you got downvoted for asking a question without searching for an answer first. https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html

jbunton10
  • 60
  • 5