2011-05-27 46 views
3

我試圖將.java文件讀入JTextArea,無論使用何種方法讀取文件,格式都不會保留。實際的代碼是確定的,但評論總是搞砸了。這是我的嘗試。如何在讀取文件時保持格式化

//Scanner: 
    //reads an input file and displays it in the text area 
     public void readFileData(File file) 
     { 
     Scanner fileScanner = null; 

     try 
     { 
      fileScanner = new Scanner(file); 
       while(fileScanner.hasNextLine()) 
       { 
        String line = fileScanner.nextLine(); 

        //output is a JTextArea 
        output.append(line + newline); 
       } 

     } 
      catch(FileNotFoundException fnfe) 
      { 
       System.err.println(fnfe.getMessage()); 
      } 
     } 


//Scanner reading the full text at once: 
    //reads an input file and displays it in the text area 
     public void readFileData(File file) 
     { 
     Scanner fileScanner = null; 

     try 
     { 
      fileScanner = new Scanner(file); 

      fileScanner.useDelimiter("\\Z"); 
      String fullText = fileScanner.next(); 

      //print to text area 
      output.append(fullText + newline); 

     } 
      catch(FileNotFoundException fnfe) 
      { 
       System.err.println(fnfe.getMessage()); 
      } 
     } 


//BufferedReader: 
    //reads an input file and displays it in the text area 
     public void readFileData(File file) 
     { 
     //Scanner fileScanner = null; 

     try 
     { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(file)); 

      String line = ""; 
      while((line = reader.readLine()) != null) 
      { 
       output.append(line + newline); 
      }    
     } 

是否有反正保持格式相同?

PS - 張貼於http://www.coderanch.com/t/539685/java/java/keep-formatting-while-reading-files#2448353

獵人

回答

2

使用JTextArea.read(...)方法。

+0

JTextArea.read工作,我會用camickr溶液(...)做幾乎完全一樣的任何我有過上述的嘗試。我最終發現的是JTextArea具有setTabSize()和getTabSize()方法,並通過將setTabSize()更改爲更小的數字,我在原始文檔中使用的選項卡正常顯示。 – 2011-05-31 16:55:51

-1

這可能是由於var新行被硬編碼爲'\ n'或類似的東西。嘗試定義換行符如下:

String newline=System.getProperty("line.separator"); 

該解決方案更是「一般」,但如果有一個JTextArea

+0

-1,JTextArea的文檔使用「\ n」來表示換行符。在Windows系統上使用line.separator屬性將嘗試在文本區域附加「\ r \ n」。 「\ r」將被解析出來。 – camickr 2011-05-27 23:45:53

相關問題