Линии, потерянные во время чтения файла в JTextPane - PullRequest
0 голосов
/ 08 июня 2011

Я читаю java-файл в JTextPane, и некоторые строки пропускаются, и я не могу найти, где, я думаю, мне просто нужен другой набор глаз, чтобы посмотреть на мой метод чтения.

/**
 * Reads a File object line by line and appends its data
 * to the JTextPane. I chose to NOT use the JTextPane's read()
 * function because it creates formatting conflicts.
 *
 * @param file      The File object to read data from
 */


    public void readFileData(File file)

  {
     Scanner fileScanner = null;

     try
     {
        fileScanner = new Scanner(file);
     }
        catch(FileNotFoundException fnfe)
        {
           System.err.println(fnfe.getMessage());
        }

     while(fileScanner.hasNextLine())
     {
        String line          = fileScanner.nextLine();
        String trimmedLine = line.trim();

            //test line for potential keywords, ignore comments
        if(!trimmedLine.contains("/**") && !trimmedLine.contains("/*") &&
           !trimmedLine.contains("//"))
        {
           boolean tst = Keywords.hasKeywords(line);
           if(tst) //keywords exist in the line, split the line up
           {
              String[] words = line.split("\\s");
              for(String word : words)
              {
                 if(Keywords.isKeyword(word))
                 {
                        //copy keyword object 
                    Keywords k = map.get(word); 
                        //append keyword with proper color
                    ui.append(k.getText() + " ", k.getColor());
                 }
                 else //not a keyword append normally
                 {
                    ui.append(word + " ", Color.BLACK);
                 }
              }
              ui.append(newline);
           }
           else //if the line had no keywords, append without splitting
           {
              ui.append(line, Color.BLACK);
              ui.append(newline);
           }
        }
        else 
        {
                //create darker color, because the built-in 
                    //orange is too bright on your eyes
           Color commentColor = Color.ORANGE.darker().darker();

            //if this is the start of a multiline comment
           if(trimmedLine.startsWith("/**") || trimmedLine.startsWith("/*") )
           {
              //while not at the end of the comment block
              while(!trimmedLine.endsWith("*/"))
              {
                 //append lines
                 ui.append(line, commentColor);
                 ui.append(newline);

                    //ensure more lines exist
                 if(fileScanner.hasNextLine())
                 {
                    line = fileScanner.nextLine();
                    trimmedLine = line.trim();
                 }
              }
                //append the ending line of the block comment, has '*/'
              ui.append(line, commentColor);
              ui.append(newline);
           }
           else if(trimmedLine.startsWith("//")) //start of single line comments
           {
              ui.append(line, commentColor);
              ui.append(newline);
           }//end if
        }//end if
     }//end while
            fileScanner.close();
  }//end readFileData()

Любая помощь будет отличной.

Hunter

также размещено по адресу: http://www.coderanch.com/t/541081/java/java/Lines-lost-during-reading-file#2454886

Ответы [ 4 ]

1 голос
/ 08 июня 2011

Ваш код не будет выводить строки, которые выглядят следующим образом:

    int example /* my example is 3 */ = 3;
    for (int i = 0; i < 3; i ++) { // process now.   ... 

    } // okay I'm done.

комментарии могут не начинаться с начала обрезанной строки.

1 голос
/ 08 июня 2011

Проблема возникает здесь:

//ensure more lines exist
             if(fileScanner.hasNextLine())
             {
                line = fileScanner.nextLine();
                trimmedLine = line.trim();
             }

Вы заменяете строку новой строкой, и только потом добавляете ее. Таким образом, исходная строка заменяется новой перед любым добавлением.

0 голосов
/ 08 июня 2011

Вы должны попробовать запустить свой метод в потоке отправки событий Swing. Возможно, у вас есть проблемы с потоками.

Если это проблема, для производительности вы должны прочитать файл в каком-то потоке и отправить результат в графический интерфейс, как только у вас будет весь файл в виде строки.

0 голосов
/ 08 июня 2011

вы можете попробовать

String s;
if ((s = fileScanner.nextLine()) != null) {
    trimmedLine = s.trim();
    //do stuff
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...