繁体   English   中英

如何将.txt文件中的整数保存到数组中?

[英]How to save integers from a .txt file into an array?

所以我有一个数组int []数字= {1,2}; 但我希望将1,2删除并替换为txt文件中的数字。 我可以使用以下方法从控制台中的文件中看到数字:

public String[] readLines(String filename) throws IOException {
    FileReader fileReader = new FileReader(filename);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    List<String> lines = new ArrayList<String>();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
    }
    bufferedReader.close();
    return lines.toArray(new String[lines.size()]);
}

public static void testFileArrayProvider() throws IOException {
    algo1 fap = new algo1();
    String[] lines = fap
            .readLines("D:/Users/XXX/workspace/abc/src/abc1/Filename123");
    for (String line : lines) {
        System.out.println(line);
    }
}

现在我需要将它们保存在数组中。 怎么打? xd Thx伙计们

这应该工作:

   // In your case this is already populated
   String[] lines = new String[] {"123", "4567"};


    // Easier to work with lists first
    List<Integer> results = new ArrayList<>();
    for (String line : lines) {
        results.add(Integer.parseInt(line));
    }

    // If you really want it to be int[] for some reason
    int[] finalResults = new int[results.size()];

    for (int i = 0; i < results.size(); i++) {
        finalResults[i] = results.get(i);
    }

    // This is only to prove it worked
    System.out.println(Arrays.toString(finalResults));

在Java-8中,您可以将其缩短为

int[] finalResults = Arrays.stream(lines).mapToInt(Integer::parseInt).toArray();

暂无
暂无

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

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