简体   繁体   中英

Read data from text file with scanner and multiple delimiters in JAVA

I have a text file containg the following data:

20;
1: 39, 63;
2: 33, 7;
16: 33, 7;
3: 45, 27;
4: 8, 67;
5: 19, 47;
6: 15, 40;
...
20: 65, 54;

first integer is the amount of entries in the list.

Each line is an entry. So entry 1 has xy coordinates 39 and 63 respectively. I understand that I can use different delimiters to read the data, but i'm not quite sure how to achieve that. Currently I'm using split() .

The following code reads each line, but this obviously doesn't work since the delimiters are not set propperly. Is there a good way to get this to work?

String[] temp = sc.next().split(";");
int productAmount = Integer.parseInt(temp[0]);
sc.nextLine();

for (int i = 0; i < productAmount; i++) {
    int productID = sc.nextInt();
    int x = sc.nextInt();
    int y = sc.nextInt();
    Product product = new Product(x, y, productID);
    productList.add(product);
}

All of the tokens can be converted to integers after removing the last character from them. You can make use of this property of the given data. Define a method like this:

int integerFromToken(String str) {
    return Integer.valueOf(str.substring(0, str.length() - 1));
}

which returns the integer part of a token ( 39, returns 39 , 63; returns 63 etc.). Now use the method to get integer values from tokens (obtained with sc.next() ):

int productID = integerFromToken(sc.next());
int x = integerFromToken(sc.next());
int y = integerFromToken(sc.next());

If you use

String[] temp = sc.next().split("[ ,:;]");

then your temp variable will hold only the numbers. The string "[ ,:;]" is a regular expression , and it means any character in the square brackets will be a delimiter.

Very similar to what Croo said, but I get a compilation error when I use his method.

In order to avoid matching empty strings by including spaces as delimiters, it makes more sense to me to allow them and use a call to trim to get rid of them.

Also it be useful to know that the Scanner can be given a regex expression as a delimiter and then calls to next can be used to navigate the input.

sc.useDelimiter("[,:;]");
int productAmount = Integer.parseInt(sc.next());
int x, y, productID, i;
for (i = 0; i < productAmount; i++) {
    productID = Integer.parseInt(sc.next().trim());
    x = Integer.parseInt(sc.next().trim());
    y = Integer.parseInt(sc.next().trim());
    productList.add(new Product(x,y,productID));
}

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