我正在讀取一個Java文件到JTextPane中,並且一些行被越過,我似乎無法找到位置,我想我只是需要另一組眼睛來查看在我的閱讀方法。閱讀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()
任何幫助將是偉大的。
獵人
張貼於:http://www.coderanch.com/t/541081/java/java/Lines-lost-during-reading-file#2454886
你把它扔進一個調試器,並通過它?文件內容是什麼樣的? – ProfessionalAmateur 2011-06-08 18:42:13
文件內容是一個java文件,由於某種原因,這個錯誤只發生在大文件中。我希望避免跨越這個龐大的文件,但我可能不得不。 – 2011-06-08 18:51:24
您不必一步步完成所有操作,直到第一次出現您所看到的錯誤。代碼不會很長,您可以減少輸入文件以進行快速測試。 – ProfessionalAmateur 2011-06-08 20:00:05