简体   繁体   中英

I want to read data from a line in a file. in Java

I'm currently trying to read certain data from multiple lines(from a specified file) in java.

For example with the lines below i want to store the numerical values from each line in an array, i don't want to read the entire line into an array(i can do that already)

      Firstname 100700 Lastname
      Firstname 260000 Lastname
      Firstname 303000 Lastname
      Firstname 505050 Lastname

How would i go about putting something in my code which allows the program to read the numerical data in my scenario.(Btw the spaces are supposed to be there) BufferedReader input;

    input = new BufferedReader(new FileReader("file.txt"));// file to be read from
    String Line;
    int i = 0;
    int[]number=new int[4];
    while (Line != null)
    {
        Line = input.readLine(); 

       // Then i would need something down here to read the numerical values?
        number[i]=????

        i++
    }

Any help would be appreciated.

Thanks.

Hava a look on String.split() and Integer.parseInt() .

You can use Line.split(" ") to split your String into a String[] and then use Integer.parseInt(myArray[1]) to get the number as an int .

Also note: in java, the convention is that variables start with lower case letter, so you should consider renaming Line -> line

input = new BufferedReader(new FileReader("file.txt"));// file to be read from
String line;
int i = 0;
int[]number=new int[4];
while (line != null)
{
    line = input.readLine(); 
    // here is my refinement
    String[] x = line.Split();
    System.out.println("FirstName: " + x[0]);
    System.out.println("Number: " + x[1]);
    System.out.println("LastName: " + x[2]);

    i++
}

Try this

String line = input.readLine();
if (line != null) {
   int number = Integer.parseInt(line.replaceAll("[^\\d]", ""));
   ...
}

Scanner has .hasNextInt() and .nextInt() . You can use those to read the numbers. Otherwise you could just use some regexes with the Pattern class, or use amit's suggestion.

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