简体   繁体   中英

Reading integers from a file separated by space in java

Input file containing integers will be like this:

     5 2 3 5
     2 4 23 4 5 6 4

So how would I read the first line, separate it by space and add these numbers to Arraylist1. Then read the second line, separate it by space and add the numbers to ArrayList2 and so on. (So Arraylist1 will contain [5,2,3,5] etc)

    FileInputStream fstream = new FileInputStream("file.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String data;
    while ((data = br.readLine()) != null)   {
      //How can I do what I described above here?
    }

Homework?

You can use this:

String[] tmp = data.split(" ");    //Split space
for(String s: tmp)
   myArrayList.add(s);

Or you have a look at the Scanner class.

Consider using a StringTokenizer

Some help : String tokenizer

StringTokenizer st = new StringTokenizer(in, "=;"); 
while(st.hasMoreTokens()) { 
String key = st.nextToken(); 
String val = st.nextToken(); 
System.out.println(key + "\t" + val); 
} 

You can get a standard array out of data.split("\\\\s+"); , which will give you int[]. You'll need something extra to throw different lines into different lists.

After I tried the answer provided by HectorLector, it didn't work in some specific situation. So, here is mine:

String[] tmp = data.split("\\s+");    

This uses Regular Expression

what you would require is something like an ArrayList of ArrayList . You can use the data.split("\\\\s+"); function in java to get all the elements in a single line in a String array and then put these elements into the inner ArrayList of the ArrayList of ArrayLists. and for the next line you can move to the next element of the outer ArrayList and so on.

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