2016-04-24 86 views
-5

我正在嘗試使用Java編寫文本編輯器,但似乎無法使「打開文件」功能正常工作。當我運行代碼時,它只顯示文件的第一行。我已經嘗試了所有來自How to read a large text file line by line using Java?的代碼片段,但它仍只讀取第一行。爲什麼我不能讀取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

顯示你的嘗試。 –

+2

*「但它仍只讀取第一行。」*您的代碼不會這樣做。請創建一個[mcve]。 – Tom

+0

也許你需要一個StringBuilder並把一些新的行放到你的輸出中? –

回答

相關問題