public class FtpUtil {
FtpClient ftpClient;
/**
* 连接FTP服务
* @param url //IP地址
* @param port//端口号
* @param username//用户名
* @param password//密码
* @return
*/
public static FtpClient connectFTP(String url, int port, String username, String password) {
//创建ftp
FtpClient ftp = null;
try {
//创建地址
SocketAddress addr = new InetSocketAddress(url, port);
//连接
ftp = FtpClient.create();
ftp.connect(addr);
//登陆
ftp.login(username, password.toCharArray());
ftp.setBinaryType();
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ftp;
}
/**
* 取ftp上的文件内容
* @param ftpFile
* @param ftp
* @return
*/
public static List<String> download(String ftpFile, FtpClient ftp) {
List<String> list = new ArrayList<String>();
String str = "";
InputStream is = null;
BufferedReader br = null;
try {
// 获取ftp上的文件
is =
ftp.getFileStream(ftpFile);
//转为字节流
br = new BufferedReader(new InputStreamReader(is));
while((str=br.readLine())!=null){
list.add(str);
}
br.close();
}catch (FtpProtocolException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
FtpClient ftp = connectFTP("ip地址,"用户名","密码");
List<String> list = download("文件路径",ftp);
for(int i=0;i<list.size();i++){
String strOut = null;
if(list.get(i).toString()!=null){
try {
byte[] bs = list.get(i).toString().getBytes();
strOut = new String(bs, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(strOut);
System.out.println(list.get(i).toString());
}
}
}