【发布时间】: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
批量。
【问题讨论】: