Java中将字符串转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9733060/
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-08-16 06:52:32  来源:igfitidea点击:

convert String to Array in Java

javaarraysstring

提问by SuShiS

I have a txt file like this:

我有一个这样的txt文件:

5
1
3
6
9

5
1
3
6
9

I want to read them using java and store all of the numbers into a array.How do I do that? read them in as string and convert to arrray? (how to convert?) the file only contain ints.

我想使用 java 读取它们并将所有数字存储到一个数组中。我该怎么做?将它们作为字符串读入并转换为数组?(如何转换?)该文件仅包含整数。

I tried read them into a string and use this to convert

我尝试将它们读入一个字符串并使用它来转换

 static public int[] strToA(String str)
{
    int len = str.length();
    int[] array = new int[len];
    for (int i = 0; i < len; i++)
    {
        array[i] = Integer.parseInt(str.substring(i,i+1));
    }
    return array;
}

采纳答案by ch4nd4n

Code would be something like this. This is untested code and may have Syntax errors.

代码将是这样的。这是未经测试的代码,可能有语法错误。

Path file = "yourfile";
// open file
try (InputStream in = Files.newInputStream(file);
    BufferedReader reader =
      new BufferedReader(new InputStreamReader(in))) {
    String line = null;
    intArr = new int[10]; // bad code could fail if file has more than 10
    int i = 0;
    while ((line = reader.readLine()) != null) {
        intArr[i++] = Integer.parseInt(line); // parse String to int
    }
} catch (IOException x) {
    System.err.println(x);
}

To use List instead of array change line

使用 List 而不是数组更改行

intArr = new int[10];

to

List intArr = new ArrayList();

Code would be something like

代码将类似于

    List intArr = new ArrayList();
    while ((line = reader.readLine()) != null) {
        intArr.add(Integer.parseInt(line)); // parse String to int
    }

回答by Tim

Scanner can help you read your file, and you can use a Listor something else to store the info.

Scanner 可以帮助您阅读您的文件,您可以使用 aList或其他东西来存储信息。

After that, you can use this Listto convert your Array.

之后,您可以使用它List来转换您的Array.

回答by fanzhang

public static Integer[] read2array(String filePath) throws IOException {
    List<Integer> result = new ArrayList<Integer>();
    RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");
    String line = null;
    while(null != (line = randomAccessFile.readLine())) {
        result.add(new Integer(line));
    }
    randomAccessFile.close();
    return result.toArray(new Integer[result.size()]);
}