简体   繁体   中英

java using append to extract data from a line of a file

I am extremely new to Java, as you can tell from my code. Any help is welcome :)

I have a file contains lines like:

Columns in File: 7

Exact File Quantity (Rows): 118

Exact File Record Length (Bytes in Variable Block): 52

I want to use append to extract the numbers after the label, but it returns zero, not the actual number after the label. Here is what I have:

   public int extractVariables(String aLine)
   {
    Scanner scan = new Scanner(actualFile);
    while(scan.hasNext())
    {
        String line = scan.nextLine();
        if(line.contains("Columns in File:"))
        {
            StringBuilder numOfVariables = new StringBuilder();
            for(int i = 16; i < line.length(); i++)
            {
                numOfVariables.append(charAt(i)).trim();
            }
      // check if the information is missing
                if(numOfVariables != null && !numOfVariables.equals(""))
                {
                    int variables = Integer.parseInt(numOfVariables);
                }
                else
                {
                    System.out.print("Number of varibales is missing!");
                }
            }
            return variables;
        }
    }

Also, I ask the user to input a file using command line argument, and store the file into actualFile, like this:

      try{
          File actualFile = new File(args[0]);
          System.out.println("File was processed: true");
         }
      catch (ArrayIndexOutOfBoundsException e)
        {
            System.out.println("File was processed: false. Re-enter filename.");
            return;
        }

So I put actualFile for the scanner to open the file and reads the lines, does the scanner reads the correct file? Maybe that's why the method returns zero?

Instead of doing

for(int i = 16; i < line.length(); i++)
        {
            numOfVariables.append(charAt(i)).trim();
        }

It seems better to make use of nextInt(); So, the code would look something like this:

line.nextInt();

Also, to check if there is a number or if it is missing, you can use:

if(line.hasNextInt()) {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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