2014-01-17 3 views
0

텍스트 파일에서 텍스트를 읽으려고하는데 system.out.print를 사용하여 이미 시스템에서 인쇄 할 수 있습니다. 하지만 텍스트 파일에서 읽은 텍스트에서 JTextArea의 텍스트를 설정하면 "스레드의 예외"주 "java.lang.NullPointerException"이 표시됩니다. 실제로 인쇄 라인이 잘 돌아가고 있고 원하는 것을 이미 읽을 수는 있지만이 텍스트를 JTextArea에 넣을 수는 없습니다. 어떻게해야합니까? 여기 각 줄의 특정 문자 수 이내의 텍스트 파일 읽기

내 코드입니다 :

package mdiforms; 
    import java.io.BufferedReader; 
    import java.io.FileReader; 

    public class FR 
    { 
    public static void main (String[] args) throws Exception 
    { 
      String path = ("C:/Users/Pasusani/Desktop/try.txt"); 
    FileReader file = new FileReader(path); 
     BufferedReader reader = new BufferedReader(file); 

    String text = ""; 
    String line = reader.readLine(); 
    while (line !=null) 
    { 
     text += line; 
     line = reader.readLine(); 
       String setText = line.substring(0,1); 
      txtLine.setText(setText); 
    } 
    System.out.println(text); 

    }  

} 
+1

JTextArea에 삽입하려는 코드 스 니펫을 게시 할 수 있습니까? – omgBob

+2

실제 코드를 게시하십시오. 'txtLine'은 어디에도 없습니다. –

+1

'txtLine'을 초기화하지 않았습니다. – Maroun

답변

0
당신의 JTextArea에 txtLine 개체가 초기화되지

, txtLine = new javax.swing.JTextArea();

0

가 JTextArea에 출력 스트림을 리디렉션이 같은 설정 출력 스트림을 사용해보십시오 :

.... 
    { 
    OutputStream out1 = new OutputStream() { 
     @Override 
     public void write(final int b) throws IOException { 
      updateTextPane(String.valueOf((char) b)); 
     } 

     @Override 
     public void write(byte[] b, int off, int len) throws IOException { 
      updateTextPane(new String(b, off, len)); 
     } 

     @Override 
     public void write(byte[] b) throws IOException { 
      write(b, 0, b.length); 
     } 
    }; 

    System.setOut(new PrintStream(out1, true)); 
    } 
    .... 

    private void updateTextPane(final String text) { 
    SwingUtilities.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      Document doc = jTextArea.getDocument(); 
      try { 
       doc.insertString(doc.getLength(), text, null); 
      } catch (BadLocationException e) { 
       throw new RuntimeException(e); 
      } 
     } 
    }); 
} 

현재 System.out.println(text);을 사용합니다. 콘솔에없는 jTextArea에 텍스트를 인쇄합니다.