如何在JAVA中读取.txt文件的特定部分

我一直试图弄清楚如何从.txt文件中读取。 我知道如何阅读整个文件,但我在阅读文件中两个特定点之间遇到困难。 我也试图使用扫描仪类,这是我到目前为止:

public void readFiles(String fileString)throws FileNotFoundException{ file = new File(fileString); Scanner scanner = null; line=""; //access file try { scanner = new Scanner(file); } catch (FileNotFoundException e) { System.out.println("File not found."); } // if more lines in file, go to next line while (scanner.hasNext()) { line = scanner.next(); if (scanner.equals("BGSTART")) //tag in the txt to locate position { line = scanner.nextLine(); System.out.println(line); lb1.append(line); //attaches to a JTextArea. window2.add(lb1);//adds to JPanel } } 

.txt文件看起来像这样:

BGSTART //内容BGEND

运行程序时,面板上没有任何内容。

我试图在这两点之间阅读。我没有很多从txt文件阅读的经验。 有什么建议么? 谢谢。

假设BGSTARTBGEND处于单独的行,根据@ SubOptimal的问题,你需要这样做:

 boolean tokenFound = false; while (scanner.hasNextLine()) { line = scanner.nextLine(); //line, not scanner. if (line.equals("BGSTART")) //tag in the txt to locate position { tokenFound = true; } else if (line.equals("BGEND")) { tokenFound = false; } if(tokenFound) { System.out.println(line); lb1.append(line); //attaches to a JTextArea. window2.add(lb1);//adds to JPanel } } 

一些改进:

 try { Scanner scanner = new Scanner(new FileInputStream(file)); //Moved the rest of the code within the try block. //As it was before, if there where any problems loading the file, you would have gotten an error message (File not found) //as per your catch block but you would then have gotten an unhandled null pointer exception when you would have tried to //execute this bit: scanner.hasNextLine() boolean tokenFound = false; while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); //line, not scanner. if (line.equals("BGSTART")) //tag in the txt to locate position { tokenFound = true; } else if (line.equals("BGEND")) { tokenFound = false; } if ((tokenFound) && (!line.equals("BGSTART"))) { System.out.println(line); //I am not sure what is happening here. //lb1.append(line); //attaches to a JTextArea. //window2.add(lb1);//adds to JPanel } } } catch (Exception e) { System.out.println("File not found."); } 

文件内容:

 do not show line one do not show line two BGSTART this is a line this is another line this is a third line BGEND do not show line three do not show line four 

你为什么不使用子串? 一旦找到了BGSTART和BGEND,就可以在下面代码行中的某处捕获字符串:

  StringBuilder sb= new StringBuilder(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); sb.append(line); } String capturedString = sampleString.substring(sb.toString().indexOf("BGSTART"), sb.toString().indexOf("BGEND")); 

希望这可以帮助

几乎不错,但你在做:

  if (scanner.equals("BGSTART")) //tag in the txt to locate position 

您应该line变量而不是scanner查找文件内容。
所以试试这个:

  if (line.equals("BGSTART")) //tag in the txt to locate position