如何用Java编写代码以读取JPA中的过程并将其写入FTP路径中的CSV文件

 List<Object[]> result=null;
        try {
            em = getEntityManager();
            if(null!=em){
                Query query =   em.createNativeQuery("{call procedure Name('"+geoLocationName+"')}"); 
                result =query.getResultList(); 
            }else{
                logger.info("Connection is not successfull");
            }
        }catch (Exception ex) {
            logger.error("Error while fetching data from ::"+ex.getMessage());
        } finally {
            if(null!=em){

                em.close();

            }

        }

我正在使用上面的代码阅读过程

现在,我如何将结果写入到csv文件中,而该文件必须存储在ftp路径中而不存储在本地。

评论
懒喵喵~
懒喵喵~

您必须使用Apache Commons CSV和Apache Commons Net来完成工作。

首先,创建两种方法->一种将文件保存在FTP上,另一种创建CSV文件:

public void saveFileonFTP(File file) throws IOException {
  FTPClient ftpClient = new FTPClient();
  ftpClient.connect("put here url");
  ftpClient.login("put here ftp user name", "put here ftp password", "put here the user account for which you to do");
  try(FileInputStream stream = new FileInputStream(file)) {
     ftpClient.storeFile(file.getName(), stream);
     ftpClient.logout();    
  }
}

public File writeToCSV(List<Object[]> result) throws IOException {
   File csvFile = new File("D:/abc.csv");
   csvFile.createNewFile();
   try (FileWriter writer = new FileWriter(csvFile ); 
        CSVPrinter csvPrint= new CSVPrinter(writer, CSVFormat.DEFAULT);
    ) {
      for(Object[] obj : result) {
        // example  
        csvPrint.printRecord(obj[0],obj[1],...);
      } 
   }
   return csvFile;
}

public void callProcedure(String geoLocationName) {
  List<Object[]> result=null;
    try {
        em = getEntityManager();
        if(null!=em){
            Query query = em.createNativeQuery("{call procedure Name('"+geoLocationName+"')}"); 
            result = query.getResultList(); 
        } else {
            logger.info("Connection is not successful");
        }
        File csvFile = writeToCSV(result);
        saveFileOnFTP(csvFile);  
    }catch (Exception ex) {
        logger.error("Error while fetching data from ::"+ex.getMessage());
    } finally {
        if(null!=em){
            em.close();
        }

    }

}
点赞
评论