简体   繁体   中英

Trouble reading from file in java (difficult format)

I'm trying to read from a file, and store the values in variables. The problem is that each line in the file is a mix of integers and strings, with an uneven number of spaces/tabs between them. I know what the first 4 elements in the line are, but then there are a sequence of numbers that differs in length (but these numbers are terminated by a 0). I have tried some different approaches, but I can't seem to get it right. First I tried to read a line one by one, split it when it sees a space, and then store the values that does not consist of blank spaces into a new array. This didn't work as it didn't split "well enough". One index in the array could consist of a string, many spaces and then an int. I have tried som other variants of this, but I just can't seem to think of a good way. Is there anyone that could give me some pointers on how to read this sort of file?

Here is an example of a line in the file: 7 Carpet 8 4 5 9 1 2 0

Ex. of split:

while (in.hasNextLine()) {
   line = in.nextLine();
   String[] splitLine = line.split(" ");
}

I also tried using split("\\t")

Try replacing

line = line.split(" ");

with

line.split("\\s+");

This will split the line based upon white space rather than a single space. This means it will account for multiple spaces, tabs, etc.

To split properly when you get to a space you have to use

line = line.split("\\s+");

This is because " " is considered a special character in Java.
line = line.split("\\\\s"); would be used if it was single spaces but to do many spaces do first one.

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