Hunter McMillen
Hunter McMillen

Reputation: 61530

How to keep formatting while reading files

I'm trying to read a .java file into a JTextArea and no matter what method I use to read in the file the formatting is never preserved. The actual code is ok but the comments always get messed up. 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 anyway to keep the formatting the same??

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

Hunter

Upvotes: 3

Views: 1608

Answers (2)

Soronthar
Soronthar

Reputation: 1601

It may be due the var newline being hardcoded as '\n' or something like that. Try defining newline as follows:

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

This solution is more "general", but I would use camickr solution if working with a JTextArea

Upvotes: -1

camickr
camickr

Reputation: 324147

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

Upvotes: 2

Related Questions