如何在读取文件时保持格式化

时间:2011-05-27 20:19:13

标签: java

我正在尝试将.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 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:-1)

可能是因为var换行符被硬编码为'\ n'或类似的东西。尝试按如下方式定义换行符:

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

此解决方案更“通用”,但如果使用JTextArea,我会使用camickr解决方案