簡體   English   中英

java stream 將批處理字符串寫入文件

[英]java stream writing batch String in to file

我有一個list object,其中包含我想逐批將其寫入文件的字符串值。

在我下面的代碼中,批處理值為 4。因此,我希望將 4 個字符串值從批處理 1 寫入文件。 下一批(第 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

在批次。

該聲明:

int fullChunks = (size - 1) / length;

將導致 6 - 1 / 4。因為這些是整數,所以向下舍入,所以結果將是 5/4 = 1。

在 IntStream 中,您采用范圍形式 0、2(上限不是范圍的一部分),因此 2 個元素導致 0、1。如果您想要列表本身的值而不是使用mapToObj(i -> source.get(i).toString())而不是.mapToObj(String::valueOf)

不清楚你想用批處理完成什么,因為結果都寫到同一個文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM