将txt文件的内容存储在数组中

时间:2016-04-15 01:35:23

标签: java

我有一个类似43 78 63 73 99 ....的.txt文件,即。 它的所有值都用空格分隔。 我希望将它们中的每一个都添加到数组中,这样 a[0]=43 a[1]='78 a[2]=63等等。 我怎么能用Java做这个...请解释

4 个答案:

答案 0 :(得分:0)

将文件读入字符串。然后将空格上的字符串溢出到字符串数组中。

答案 1 :(得分:0)

使用文件阅读器读取值

E.g。

Scanner sc = new Scanner(new File("yourFile.txt"));

然后从文件中读取所有整数并将它们放入整数数组中。

Java Scanner class documentation

Java File class

答案 2 :(得分:0)

我会通过将文本文件存储到字符串中来实现。 (只要它不是太大)然后我会使用.split(“”)将它存储到一个数组中。

像这样:

String contents = "12 32 53 23 36 43";
//pretend this reads from file

String[] a = contents.split(" ");

现在数组'a'应该包含所有值。如果希望数组为int,则可以使用int数组,并使用Integer.toString()转换数据类型。

答案 3 :(得分:0)

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class readTextToIntArray {
public static void main(String... args) throws IOException {
    BufferedReader reader=new BufferedReader(new FileReader("/Users/GoForce5500/Documents/num.txt"));
    String content;
    List<String> contentList=new ArrayList<String>();
    while((content=reader.readLine())!=null){
        for(String column:content.split(" ")) {
            contentList.add(column);
        }
    }
    int[] result=new int[contentList.size()];
    for(int x=0;x<contentList.size();x++){
        result[x]=Integer.parseInt(contentList.get(x));
    }
}
}

你可以使用它。

相关问题