您的位置:首页 > 编程语言 > PHP开发

ftp下载,解析txt文件入库

2017-11-07 10:17 639 查看
1、ftp下载

     /**
* 下载文件
*
* @param localPath
* @param remotePath
* @param remoteFile
*/
public void download(String localPath, String remotePath, String remoteFile) {

try {
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
createDirectory(remotePath, ftpClient);
// 获取远程路径文件列表
FTPFile[] remoteFiles = ftpClient.listFiles();

// 检查远程文件是否存在
if (remoteFiles.length < 1) {
log.error("远程文件夹:"+remotePath+"中文件为空或不存在!");
throw new RuntimeException("远程文件夹:"+remotePath+"中文件为空或不存在!");
}

log.info("开始下载远程文件: " + remotePath + remoteFile + " 到本地路径: "
+ localPath);
boolean isDownload = false;
for (FTPFile file : remoteFiles) {
if (file.getName().equals(remoteFile)) {
File localFile = new File(localPath + "/" + remoteFile);
createDirectory(localFile, localPath);
OutputStream out = new FileOutputStream(localFile);
isDownload = ftpClient.retrieveFile(remoteFile, out);
log.info("远程文件: " + remotePath + remoteFile + " 下载成功!");
out.close();
}
}

if (!isDownload) {
log.error("远程文件: " + remotePath + remoteFile + "下载失败或不存在!");
System.out.println();
throw new RuntimeException("远程文件: " + remotePath + remoteFile
+ "下载失败或不存在!");
}
} catch (Exception e) {
log.error(e);
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
2、解析txt文件

   private List<String> readEkeyFile(String filePath){
List<String> list = new ArrayList<String>();
try {
String encoding = "UTF-8";
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
list.add(lineTxt.trim());
// System.out.println(lineTxt);
}
read.close();
file.delete();
log.info("读取ekey文件内容成功");
// System.out.println(list.get(0).split(",")[0]);
} else {
log.info("找不到指定的文件");
throw new Exception("文件不存在!");
}
} catch (Exception e) {
log.info("读取文件内容出错"+e.toString());
throw new RuntimeException();
}
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ftp