I want to create a Java program which reads lines from a txt file and inserts them one by one using SQL query:
Stream<String> stream = Files.lines(Paths.get("C:\\in_progress\\test.txt"), StandardCharsets.UTF_8);
stream.forEach(System.out::println);
List<String> result = stream.collect(Collectors.toList());
for(String list : result)
{
System.out.println(list);
Thread.sleep(1000);
ProcessedWords obj = ProcessedWords.builder()
.keyword(list)
.createdAt(LocalDateTime.now())
.build();
processedWordsService.save(obj);
}
}
I see the lines printed but no SQL query is generated. Do you know where I might be wrong?
CodePudding user response:
I don't get it why you type
Thread.sleep(1000);
but all is right!
You can try execute your code without this line? Another option is that your processedWordsService is not working!
CodePudding user response:
Stream is already used by
stream.forEach(System.out::println);
The collect
operation is moot. Stream has already been used. You would need to create a new stream at this point.
For instance: in the following, the second operation on stream will throw an exception (Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
):
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
Stream<Integer> integerStream = intList.stream()
integerStream.forEach(System.out::println);
var v = integerStream.collect(Collectors.toList()); // <-- throws exception
Are you sure, you do not see this exception in your logs?
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html