java上传文件到FTP

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;


public class PdfToFtp {
    public static void main(String[] args) {
        upload();
//        download();
    }

    /**
     * 上传单个文件
     */
    public static void upload() {
        FTPClient ftpClient = new FTPClient();
        FileInputStream fis = null;
        OutputStream outputStream=null;
        int reply;
        try {
            ftpClient.connect("192.168.1.133");
            ftpClient.login("111111", "111111");
            System.out.print("连接到服务"+ftpClient.getReplyString()); 
            reply = ftpClient.getReplyCode();
            System.out.print(reply); 
            System.out.print(FTPReply.isPositiveCompletion(reply));
            if (!FTPReply.isPositiveCompletion(reply)) {
//            	ftpClient.disconnect();
                System.out.print("FTP拒绝连接");  
            }
            File srcFile = new File("F:/grails/xjmei_shop/web-app/pdf/13829297765491091.pdf");
            fis = new FileInputStream(srcFile);
            //设置上传目录
            ftpClient.changeWorkingDirectory("/report");
            

//            ftpClient.changeToParentDirectory();
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("UTF-8");
            //设置文件类型(二进制)
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
            ftpClient.setFileTransferMode(ftpClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.storeFile(new String("city=Q  永升花苑0000号;rows=1;order_4f4ce5cd-bcad-47f1-bd26-9e914bca1704_2013-10-28-10-54-020.pdf".getBytes("UTF-8"), "iso-8859-1") , fis);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP客户端出错!", e);
        } finally {
            try {
            	if(fis!=null){
            		fis.close();
            	}
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭FTP连接发生异常!", e);
            }
        }
    }

    /**
     * 下载单个文件
     */
    public static void download() {
        FTPClient ftpClient = new FTPClient();
        FileOutputStream fos = null;

        try {
            ftpClient.connect("192.168.1.133");
            ftpClient.login("111111", "111111");

            String remoteFileName = "/test.txt";
            fos = new FileOutputStream("d:/test.txt");

            ftpClient.setBufferSize(1024);
            //设置文件类型(二进制)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.retrieveFile(remoteFileName, fos);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP客户端出错!", e);
        } finally {
//            IOUtils.closeQuietly(fos);
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭FTP连接发生异常!", e);
            }
        }
    }
} 

### 使用 Java文件上传FTP 服务器特定目录 为了实现通过 JavaFTP 服务器上的指定路径上传文件的功能,可以利用 Apache Commons Net 库中的 `FTPClient` 类来完成此操作。下面是一个完整的例子,展示了如何连接到 FTP 服务器并把本地文件传输给定的目标位置。 #### Maven依赖项 首先,在项目的pom.xml中加入所需库: ```xml <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.8.0</version> </dependency> ``` #### Java代码实例 接着编写用于执行实际上传工作的Java程序: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import java.io.FileInputStream; import java.io.IOException; public class FtpUploadExample { public static void main(String[] args) { String server = "your_ftp_server_address"; int port = 21; // Default FTP Port String user = "username"; String pass = "password"; try (FTPClient ftpClient = new FTPClient()) { ftpClient.connect(server, port); boolean loginSuccess = ftpClient.login(user, pass); if (!loginSuccess){ System.out.println("Failed to log into the FTP Server."); return; } ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // Specify remote directory path on FTP server where you want to upload file. String remoteDirPath = "/path/to/directory/"; // Change working directory of FTP client instance to specified one. ftpClient.changeWorkingDirectory(remoteDirPath); File localFile = new File("/local/path/to/file.txt"); try (FileInputStream inputStream = new FileInputStream(localFile)) { String fileNameOnServer = "file_on_server_name.txt"; Boolean done = ftpClient.storeFile(fileNameOnServer ,inputStream ); if(done){ System.out.println("The file was uploaded successfully!"); }else{ System.out.println("There was an error uploading the file..."); } } ftpClient.logout(); ftpClient.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } } } ``` 这段代码实现了与FTP服务器建立连接、切换工作目录以及发送文件的过程[^3]。注意替换其中的变量值以匹配具体的环境需求,比如服务器地址、端口号、用户名密码等信息,并确保所提供的目标文件夹存在且具有写权限。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值