【问题标题】:java stream writing batch String in to filejava流将批处理字符串写入文件
【发布时间】:2023-03-29 12:24:01
【问题描述】:

我有一个 list 对象,该对象具有字符串值,我想将其逐批写入文件。

在我下面的代码中,批处理值为 4。因此,我希望将 4 个字符串值从批处理 1 写入文件中。下一批(batch-2)它应该写入其他 4 个字符串值。

但它没有按预期工作。

请在下面找到我的代码。

public class WriteToFile {
    
    public static void batches(List source, int length) throws IOException {
        if (length <= 0)
            throw new IllegalArgumentException("length = " + length);
        int size = source.size();

        int fullChunks = (size - 1) / length;
            
        try(PrintWriter pw = new PrintWriter(Files.newBufferedWriter(
                Paths.get("C:\\Users\\Karthikeyan\\Desktop\\numbers.txt")))) {
            IntStream.range(0, fullChunks + 1).mapToObj(String::valueOf).forEach(pw::println);
            
    }
    

}

    public static void main(String[] args) throws IOException {
        List<String> list = Arrays.asList("a", "b", "c", "d", "e", "f");

        
        System.out.println("By 4:");
        batches(list, 4);
    }

}

以下内容写入我的文件中。

0
1

应该写成:

a
b
c
d
e
f

批量。

【问题讨论】:

    标签: java java-8 stream


    【解决方案1】:

    声明:

    int fullChunks = (size - 1) / length;
    

    将导致 6 - 1 / 4。因为这些是整数,所以向下舍入,所以结果将是 5/4 = 1。

    在 IntStream 中,您采用范围形式 0、2(到上限不是范围的一部分),因此 2 个元素导致 0、1。如果您想要列表本身的值而不是使用 mapToObj(i -&gt; source.get(i).toString()) 而不是 @ 987654323@

    不清楚你想用批处理完成什么,因为结果都写入同一个文件。

    【讨论】:

    • 实时,我的输入 list 对象将包含 600K 记录,我将从 Web 服务的外部系统获取这些记录。所以我想把所有的600K 记录写到一个文件中,所以我教的是逐批写。为了避免在写入时出现任何故障。这是我的想法。
    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2015-07-16
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多