简体   繁体   English

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

[英]How to read specific parts of a .txt file in JAVA

I have been trying to figure out how to read from a .txt file. 我一直在试图弄清楚如何从.txt文件读取。 I know how to read a whole file, but I am having difficulties reading between two specific points in a file. 我知道如何读取整个文件,但是在读取文件中的两个特定点之间遇到困难。 I am also trying to use the scanner class and this is what I have so far: 我也在尝试使用扫描仪类,这是我到目前为止所拥有的:

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 file looks something like this: .txt文件如下所示:

BGSTART //content BGEND BGSTART //内容BGEND

Nothing is posted onto the panel when I run the program. 运行该程序时,面板上没有任何内容。

I am trying to read it between those two points.I don't have a lot of experience in reading from txt file. 我试图在这两点之间阅读它。我没有从txt文件读取的丰富经验。 Any suggestions? 有什么建议么? Thank You. 谢谢。

Assuming that BGSTART and BGEND are on seperate lines, as per @SubOptimal's question, you would need to do this: 根据@SubOptimal的问题,假设BGSTARTBGEND位于单独的行上,则需要执行以下操作:

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
   }
}

Some improvements: 一些改进:

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.");
    }

File content: 档案内容:

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

Why don't you use substring? 为什么不使用子字符串? once you have located your BGSTART and BGEND you can capture the string between it somewhere in the lines of the below code: 找到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"));

hope this helps 希望这可以帮助

Almost good, but you are doing: 差不多不错,但是您正在做:

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

You should look for file content in line variable not scanner . 您应该line变量而不是scanner查找文件内容。
So try this: 所以试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM