Java实现对ftp的读写文件
这里仅仅是对ftp工具类的简单使用,很多东西还不是很了解。当然学以致用,先用到这里吧。
- public class FtpTest {
- /**
- * 向ftp写文件(数据)
- */
- @Test
- public void uploadFile() {
- // 要写入的文件内容
- String fileContent = "hello world,你好世界";
- // ftp登录用户名
- String userName = "admin";
- // ftp登录密码
- String userPassword = "xxxx";
- // ftp地址
- String server = "127.0.0.1";//直接ip地址
- // 创建的文件
- String fileName = "ftp.txt";
- // 指定写入的目录
- String path = "wd";
- FTPClient ftpClient = new FTPClient();
- try {
- InputStream is = null;
- // 1.输入流
- is = new ByteArrayInputStream(fileContent.getBytes());
- // 2.连接服务器
- ftpClient.connect(server);
- // 3.登录ftp
- ftpClient.login(userName, userPassword);
- // 4.指定写入的目录
- ftpClient.changeWorkingDirectory(path);
- // 5.写操作
- ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
- ftpClient.storeFile(new String(fileName.getBytes("utf-8"),
- "iso-8859-1"), is);
- is.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (ftpClient.isConnected()) {
- try {
- ftpClient.disconnect();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- /**
- * ftp下载数据
- */
- @Test
- public void downFile() {
- // ftp登录用户名
- String userName = "admin";
- // ftp登录密码
- String userPassword = "xxxx";
- // ftp地址:直接IP地址
- String server = "xxxx";
- // 创建的文件
- String fileName = "ftp.txt";
- // 指定写入的目录
- String path = "wd";
- // 指定本地写入文件
- String localPath="D:\\";
- FTPClient ftp = new FTPClient();
- try {
- int reply;
- //1.连接服务器
- ftp.connect(server);
- //2.登录服务器 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
- ftp.login(userName, userPassword);
- //3.判断登陆是否成功
- reply = ftp.getReplyCode();
- if (!FTPReply.isPositiveCompletion(reply)) {
- ftp.disconnect();
- }
- //4.指定要下载的目录
- ftp.changeWorkingDirectory(path);// 转移到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.equals(fileName)) {
- //6.写操作,将其写入到本地文件中
- File localFile = new File(localPath + ff.getName());
- OutputStream is = new FileOutputStream(localFile);
- ftp.retrieveFile(ff.getName(), is);
- is.close();
- }
- }
- ftp.logout();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (ftp.isConnected()) {
- try {
- ftp.disconnect();
- } catch (IOException ioe) {
- }
- }
- }
- }
- }
很多知识点是相互联系的,希望以后的例子中能够结合更多的知识点进行实例编写,这样也有助于知识的巩固。
下面是我自己项目中用到的代码
/** * 下载pdf文件 */ public String downLoadPdf(String url,String contNo,String localPdfName){ String newUrl=""; String pathUrl="172.18.100.165"; //FTP服务器hostname int port=21;//FTP服务器端口 String username="shwasextt20\\ftp"; //FTP登录账号 String password="qwerty1!"; //FTP登录密码 String remotePath="/Imagedownload";//FTP服务器上的相对路径 String fileName;//要下载的文件名 // String localPath="I:\\2015\\workspace\\workspace_newng\\wj\\WebContent\\wwwroot\\ng\\downLoad";//下载后保存到本地的路径 String localPath="C:\\project\\b2c\\cms.ear\\cms.war\\wwwroot\\ng\\downLoad";//下载后保存到本地的路径 // String localPath="C:\\B2C\\cms.ear\\cms.war\\wwwroot\\ng\\downLoad";//下载后保存到本地的路径 String localName = ""; Date date = new Date(); SimpleDateFormat dr = new SimpleDateFormat("yyyyMMddHHmmss"); //重命名(保单号+时间) localName = localPdfName; if(!"".equals(url) && url !=null){ // String backUrl = "ftp://172.18.100.165/Imagedownload/0180050037-个险合同-电子合同-201537071208(66e735db-8ddf-4e0e-b70c-339544ff630b).PDF"; fileName = url.split("/")[4]; pathUrl = url.split("/")[2]; //生产环境ftp判断 if("172.16.252.100".equals(pathUrl)){ username = "shwasextp20\\ftp"; }else if("172.16.252.110".equals(pathUrl)){ username = "shwasextp21\\ftp"; }else{ username = "shwasextt20\\ftp"; } FTPClient ftp = new FTPClient(); try { ftp.connect(pathUrl,port); ftp.login(username,password); System.out.println(ftp.isConnected()); ftp.enterLocalPassiveMode(); ftp.setControlEncoding("GBK"); ftp.setFileType(ftp.BINARY_FILE_TYPE); ftp.changeWorkingDirectory(remotePath); OutputStream outputStream = null; FTPFile[] fs = ftp.listFiles(); for (int i = 0; i < fs.length; i++) { FTPFile ff = fs[i]; if (ff.getName().equals(fileName)) { InputStream in = ftp.retrieveFileStream(new String(ff.getName().getBytes("GBK"), "ISO-8859-1")); int len = 0; long size = 0; byte[] bt = new byte[1024]; outputStream=new BufferedOutputStream(new FileOutputStream(localPath+"\\"+localName+".pdf")); while ((len = in.read(bt)) > 0) { outputStream.write(bt, 0, len); // outputStream.flush(); size = size + len; // System.out.println(fileName + "已xiazai :" + size); } newUrl = "cms/wwwroot/ng/downLoad/"+localName+".pdf"; outputStream.flush(); } } outputStream.close(); ftp.logout(); } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return newUrl; }
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术