java 从java中以空格分隔的文件中读取整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10192438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:00:59  来源:igfitidea点击:

Reading integers from a file separated by space in java

java

提问by TylarBen

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)

那么我将如何读取第一行,用空格分隔并将这些数字添加到 Arraylist1。然后阅读第二行,用空格分隔并将数字添加到 ArrayList2,依此类推。(所以 Arraylist1 将包含 [5,2,3,5] 等)

    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?
    }

回答by HectorLector

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.

或者你看看 Scanner 类。

回答by Erwald

Consider using a StringTokenizer

考虑使用 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); 
} 

回答by Thomas

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.

你可以从 中得到一个标准数组data.split("\\s+");,它会给你 int[]。您需要一些额外的东西来将不同的行放入不同的列表中。

回答by Guan Wang

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

在我尝试了 HectorLector 提供的答案后,它在某些特定情况下不起作用。所以,这是我的:

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

This uses Regular Expression

这使用正则表达式

回答by Anurag Ramdasan

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.

您需要的是类似ArrayList of ArrayList. 可以使用data.split("\\s+");java中的函数获取String数组中单行的所有元素,然后将这些元素放入ArrayLists的ArrayList的内部ArrayList中。对于下一行,您可以移动到外部 ArrayList 的下一个元素,依此类推。