Reputation: 2001
Am having a List
object having String values which i want to write it into a file by batch-by-batch.
In my below code, am having batch value as 4. so, am expecting to write 4 string values into the file from batch-1. Next batch (batch-2) it should write other 4 string values.
But its not working as expected.
Please find the my code below.
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);
}
}
Below contents are writting in my file.
0
1
It should write :
a
b
c
d
e
f
In batch.
Upvotes: -2
Views: 183
Reputation: 35
The statement:
int fullChunks = (size - 1) / length;
Will result in 6 - 1 / 4. Because these are ints it is rounded downwards so the result will be 5/4 = 1.
In IntStream you take the range form 0, 2 (to upper limmit is not part of the range) so 2 elements resulting in 0, 1. If you want the value from the list itself than use mapToObj(i -> source.get(i).toString())
instead of .mapToObj(String::valueOf)
It is not clear what you want you want to accomplish with batches, because the results are all written to the same file.
Upvotes: 0