从FTP服务器读取文件,并以字符串形式输出内容
其中包含了FTP读文件与文件转字符串两方面,需要的朋友自己拆分功能
本代码依赖commons-net-3.4.jar,请自行度娘下载
ReadFile.java
package com.crm.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
* @author DingJiaCheng
* 读取文件,转为字符串
* */
public class ReadFile {
public static String read(String path,String ftpuser,String ftppwd) {
if(path.contains("ftp:") || path.contains("FTP:")){
String ftppath = path.substring(19,43); //暂时写死
String localPath="C:\\Program Files\\hwlogstemp\\";
int reply;
FTPClient ftp = new FTPClient();
try {
ftp.connect(path.substring(6,18)); //暂时写死
//2.登录服务器 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(ftpuser, ftppwd);
//3.判断登陆是否成功
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
}
ftp.changeWorkingDirectory(ftppath);// 转移到FTP服务器目录
//5.遍历下载的目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
//解决中文乱码问题,两次解码
byte[] bytes=ff.getName().getBytes("iso-8859-1");
String fn=new String(bytes,"utf8");
if(fn.contains("json")){
//6.写操作,将其写入到本地文件中
File localFile = new File(localPath + "temp.json");
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}
ftp.logout();
path = localPath + "temp.json";
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (ftp.isConnected()){
try {
ftp.disconnect();
} catch (IOException e) {
}
}
}
}
BufferedReader reader = null;
String laststr = "";
try {
FileInputStream fileInputStream = new FileInputStream(path);
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream, "gb2312");
reader = new BufferedReader(inputStreamReader);
String tempString = null;
while ((tempString = reader.readLine()) != null) {
laststr += tempString;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return laststr;
}
public static void main(String[] args) {
String path = "ftp://123.123.123.123/abcde/defghi.txt";
String res = read(path,"username","password");
System.out.println(read(path));
}