使用org.apache.commons.net.ftp.FTPSClient上传文件

时间:2018-05-08 10:29:50

标签: java ftps

我正在使用Java API进行文件上传。 我想通过FTPS将文件上传到服务器,我发现我可以使用apache commons net的谷歌库,但是当我上传文件时我在org.apache.commons.net.ftp.FTPSClient面临问题。 以下是错误

  

线程中的异常" main"显示java.lang.NullPointerException

这是我的代码:

  public static void main(String[] args) {
            String server = "HOST";
            int port = 21;
            String user = "USER";
            String pass = "PASS";

            FTPSClient ftpClient;
            try {
                ftpClient = new FTPSClient();

            try {

                ftpClient.connect(server, port);
                ftpClient.login(user, pass);
                ftpClient.enterLocalPassiveMode();

                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

                // APPROACH #1: uploads first file using an InputStream
                File firstLocalFile = new File("TEST1.CSV");

                String firstRemoteFile = "TEST1.txt";
                InputStream inputStream = new FileInputStream(firstLocalFile);

                System.out.println("Start uploading first file");

                boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
                inputStream.close();
                if (done) {
                    System.out.println("The first file is uploaded successfully.");
                }

                // APPROACH #2: uploads second file using an OutputStream
                File secondLocalFile = new File("TEST2.CSV");
                String secondRemoteFile = "TEST2.TXT";
                inputStream = new FileInputStream(secondLocalFile);

                System.out.println("Start uploading second file");
                OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
                byte[] bytesIn = new byte[4096];
                int read = 0;

                while ((read = inputStream.read(bytesIn)) != -1) {
                    outputStream.write(bytesIn, 0, read);
                }
                inputStream.close();
                //outputStream.close();

                boolean completed = ftpClient.completePendingCommand();
                if (completed) {
                    System.out.println("The second file is uploaded successfully.");
                }

            } catch (IOException ex) {
                System.out.println("Error: " + ex.getMessage());
                ex.printStackTrace();
            } finally {
                try {
                    if (ftpClient.isConnected()) {
                        ftpClient.logout();
                        ftpClient.disconnect();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

感谢任何支持

0 个答案:

没有答案