繁体   English   中英

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

[英]convert String to Array in Java

我有一个这样的txt文件:

5
1个
3
6
9

我想使用Java读取它们并将所有数字存储到数组中,该怎么做? 以字符串形式读取它们并转换为错误? (如何转换?)文件仅包含整数。

我试着将它们读成字符串并用它来转换

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

扫描仪可以帮助您读取文件,并且可以使用List或其他方式存储信息。

之后,您可以使用此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()]);
}

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

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

使用列表而不是数组更改行

intArr = new int[10];

List intArr = new ArrayList();

代码就像

    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