JAVA: how to parse Integer numbers (limited by a variable number of spaces) in a line of a text file

I want to parse the numbers in a line of a text file line by line. For example, imagine _ as space

The contents of my text file are as follows:

___34_______45
_12___1000
____4______167
...

I think you have an idea. Each line can have a variable number of spaces separating the numbers, which means no picture at all. The simplest solution would be to read char on char and check if it is a number and gets to the end of the line and parses it. But there must be another way. How can I read this in Java automatically so that I can get a specific data structure like an array

[34,45]
[12,1000]
[4,167]
+5
source share
3 answers

java.util.Scanner. nextInt(), , . , "".

import java.util.Scanner;
public class A {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int v1 = in.nextInt(); //34
    int v2 = in.nextInt(); //45
    ...
  }
}
+11

, . , Scanner . Scanner , .

List ints:

Scanner scan = new Scanner(file); // or pass an InputStream, String
while (scan.hasNext())
{
    ints.add(scan.nextInt());
    // ...

Scanner.nextInt.

, . , Scanner.nextLine(), String. String.split :

Scanner scan = new Scanner(file); // or InputStream
String line;
String[] strs;    
while (scan.hasNextLine())
{
    line = scan.nextLine();

    // trim so that we get rid of leading whitespace, which will end
    //    up in strs as an empty string
    strs = line.trim().split("\\s+");

    // convert strs to ints
}

Scanner . Scanner , trim.

+4

, BufferedReader String split():

BufferedReader in = null;
try {
    in = new BufferedReader(new FileReader(inputFile));
    String line;
    while ((line = in.readLine()) != null) {
        String[] inputLine = line.split("\\s+");
        // do something with your input array
    }
} catch (Exception e) {
    // error logging
} finally {
    if (in != null) {
        try {
            in.close();
        } catch (Exception ignored) {}
    }
}

(If you are using Java 7, a block is finallynot needed if you are using try-with-resources.)

This will change something like ______45___23(where _ is a space) to an array ["45", "23"]. If you need these integers, it's pretty simple to write a function to convert the String array to an int array:

public int[] convert(String[] s) {
    int[] out = new int[s.length];
    for (int i=0; i < out.length; i++) {
        out[i] = Integer.parseInt(s[i]);
    }
    return out;
}
+1
source

All Articles