简体   繁体   English

在Java中将字符串转换为数组

[英]convert String to Array in Java

I have a txt file like this: 我有一个这样的txt文件:

5 5
1 1个
3 3
6 6
9 9

I want to read them using java and store all of the numbers into a array.How do I do that? 我想使用Java读取它们并将所有数字存储到数组中,该怎么做? read them in as string and convert to arrray? 以字符串形式读取它们并转换为错误? (how to convert?) the file only contain ints. (如何转换?)文件仅包含整数。

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

Scanner can help you read your file, and you can use a List or something else to store the info. 扫描仪可以帮助您读取文件,并且可以使用List或其他方式存储信息。

After that, you can use this List to convert your Array . 之后,您可以使用此List转换Array

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()]);
}

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 使用列表而不是数组更改行

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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM