Click here to Skip to main content
15,886,830 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello!

I have been trying to figure out how to read from a .txt file. 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:

C#
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:
BGSTART
//content
BGEND

I am trying to read it between those tow points.
Any suggestions?
Thank You.
Posted
Updated 16-Feb-15 4:08am
v2
Comments
ZurdoDev 16-Feb-15 10:15am    
You can read all lines into an array and then loop through. When you hit BGSTART do what you need to until you hit BGEND.
PIEBALDconsult 16-Feb-15 10:22am    
How big is the file? Is it worth reading it all in and using a Regular Expression to select the section you need?
varoag 16-Feb-15 10:26am    
there isn't too much content. About 25 lines. But I need to have it in one file and read from it.

try
Java
public void readFile(String fileString) throws IOException
 {

   File file = new File(fileString);
   Scanner scanner = null;
   String 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

   boolean gatheringData = false;

   while (scanner.hasNext())
   {
     line = scanner.next();
     if ( gatheringData )
     {
       if ( line.equals("BGEND") )
         break;

       System.out.println(line); // add this line to JTextArea

     }
     else if ( line.equals("BGSTART") )
     {
       gatheringData = true;
     }
   }
 }
 
Share this answer
 
Try this:
Java
public static void readFiles(String fileString)
        throws FileNotFoundException {

    File file = new File(fileString);
    Scanner scanner = null;
    String line = "";

    // access file
    try {
        scanner = new Scanner(file);
    } catch (FileNotFoundException e) {
        System.out.println("File not found.");
        return; // don't continue if the file is not found
    }

    // if more lines in file, go to next line
    Boolean started = false;
    while (scanner.hasNext()) {
        line = scanner.nextLine();

        if (line.equals("BGEND")) {
            started = false;
            // if you also immediately want to go out of the loop,
            // un-comment the following line:
            // break;
        }

        if (started) // tag in the txt to locate position
        {
            System.out.println(line);
            lb1.append(line); //attaches to a JTextArea.
            window2.add(lb1); //adds to JPanel
        }

        if (line.equals("BGSTART")) {
            started = true;
        }
    }
    scanner.close();
}

How does it work?

  1. It goes through the lines.
  2. It the line equals BGEND, it sets started to false.
  3. If started equals true, it performs the actions with the line such as printing it.
  4. If the line equals BGSTART, it sets started to true.

The order of these steps is important, because BGSTART and BGEND don't have to be printed themselves.

Some other changes:

  • In the catch block, you should return, because if you don't, the method continues without the scanner is created.
  • The scanner should be closed at the end.
 
Share this answer
 
v5
Comments
varoag 16-Feb-15 11:16am    
@ProgramFOX I tried your code but I get a NullPointer Exception on the while( scanner.hasNext) line.
Any suggestions?
Thomas Daniels 16-Feb-15 11:21am    
Yes, I think your file is not found. Because the scanner gets its value in the try block, but even if there's an error that gets caught, the method still continues. I edited my answer. Also, I forgot to say that your scanner should be closed -- I added scanner.close() to my code block.
varoag 16-Feb-15 11:24am    
I figured out the issue with the exception. However, for some reason the code does not print anything. It does not attach to the Panel either. That was the problem I was having earlier. Now, I changed the scanner to "line = scanner.next()" and it prints but it prints every word in a new line.
Thomas Daniels 16-Feb-15 11:25am    
Sorry about that, I commented out the code for the Panel for my testing. Fixed.
I don't know why it doesn't print, it worked fine for me.

scanner.next() always takes the first word only, so you should use scanner.nextLine() instead.
varoag 16-Feb-15 11:38am    
Ok. thx. I copied your code and it doesn't print for me. I'll keep trying on my end. Thanks again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900