How to keep formatting while reading files

I am trying to read a .java file in JTextArea and no matter what method I use to read in the file, the formatting is never saved. The actual code is ok, but the comments are always confused. Here are my attempts.

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

Is there a way to keep the formatting the same?

PS - also posted on http://www.coderanch.com/t/539685/java/java/keep-formatting-while-reading-files#2448353

Hunter

+3
source share
2 answers

Use the JTextArea.read (...) method.

+2
source

This may be due to the fact that the new var string is hardcoded as "\ n" or something like that. Try defining a new line as follows:

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

"", camickr, JTextArea

-1

All Articles