Java操作FTP,从FTP上读取指定文件,把指定文件上传到FTP

添加依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>

读取FTP中的文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static void main(String[] args) throws Exception
{
FTPClient ftpClient=new FTPClient();//import org.apache.commons.net.ftp.FTPClient;
ftpClient.connect("10.18.20.147", 21);//连接ftp
ftpClient.login("tyz_ftp", "tc_xw_ftp");//登陆ftp
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))//是否连接成功,成功true,失败false
{
ftpClient.changeWorkingDirectory("/var/ftp/home/tyzf_ftp/batchUpload");//找到指定目录

InputStream inputStream=ftpClient.retrieveFileStream("20190708SC.csv");//根据指定名称获取指定文件
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"GBK"));
String line=null;
StringBuilder stringBuilder=new StringBuilder(150);
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
String context=stringBuilder.toString();

String[] sz = context.replaceAll("\"","").split("\n");
for (int i = 0; i < sz.length; i++)
{
System.out.println(sz[i]);//输出每一行的数据
}
}
}

把文件上传到FTP

1
2
3
4
5
6
7
8
9
public static void main(String[] args) throws Exception
{
FTPClient ftpClient = new FTPClient();//import org.apache.commons.net.ftp.FTPClient;
ftpClient.connect("10.18.20.147", 21);//连接ftp
ftpClient.login("tyz_ftp", "tc_xw_ftp");//登陆ftp
ftpClient.changeWorkingDirectory("/var/ftp/home/tyzf_ftp/batchUpload");//需要把文件上传到FTP哪个目录
File file = new File("D:\\aa.txt");//需要上传的文件
System.out.println(ftpClient.storeFile(file.getName(), new FileInputStream(file)));//存储文件,成功返回true,失败false
}