如何使用保存在 Java 中的调用存储库将数据保存在 txt 文件中的每一行

How to save data every line in txt file with call repository save in Java

@Autowired
PilahRepository repoPilah;

@Autowired
PilahService pilahService;

@Autowired
private SecurityContext securityContext;

@RequestMapping(value = "/pilahFile", method = RequestMethod.POST)
public PilahFile pilahFIle() {
    String nameFile[] = pilahService.findFileName();
    Scanner sc;
    String destination;
    BigInteger userExecutor = securityContext.userId();
    PilahFile pilah = new PilahFile();
    try {
        File source = new File("D:/Kerja/txt/");
        destination = "D:/Kerja/hasil/";
        BufferedWriter writeFile;
        Date now;
        String prev = null, curr = null, next = null;
        for (File file : source.listFiles()) {
            sc = new Scanner(file);
            now = DateUtils.now();
            while (sc.hasNextLine()) {
                prev = curr;
                curr = next;
                next = sc.nextLine();
                for (int i = 0; i < nameFile.length; i++) {
                    if (StringUtils.containsIgnoreCase(nameFile[i].trim(),
                            next.substring(767).trim())) {
                        System.out.println("file name exist");
                        writeFile = new BufferedWriter(
                                new FileWriter(destination.concat(nameFile[i]).trim(), true));
                        writeFile.write(next);
                        writeFile.newLine();
                        writeFile.flush();
                        pilah.setCreatedBy(userExecutor);
                        pilah.setCreationDate(now);
                        pilah.setFlag('Y');
                        pilah.setFileName(nameFile[i]);
                        System.out.println(pilah.getFileName());
                        pilah.setLocationDir(destination);
                        pilah.setCardId(next.substring(1, 51).trim());
                        System.out.println(pilah.getCardId());
                        pilah.setOwner(next.substring(52, 102).trim());
                        System.out.println(pilah.getOwner());
                        System.out.println(pilah.toString());
                        repoPilah.save(pilah);
                    } else {
                        System.out.println("Invalid file name");
                    }
                }

            }
            sc.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return pilah;
}

你好,我是javaspring新手。请帮我。 在我的控制器中,我调用存储库 (repoPilah) 在每个循环 (while) 中保存数据,但它只是保存我的 txt 文件的最后一行。我不知道为什么,而当我在 (pilah) 对象上打印每个数据时,我可以获取每一行的数据。感谢关注

您必须为每个条目在循环内创建 pilah 对象

PilahFile pilah = new PilahFile();

将其移入循环内,每次都创建新对象以保存。