通过FTP将文件上载到VPS时出现MalformedURLException

时间:2013-07-03 20:14:03

标签: java ftp vps uploading

我在通过FTP将文件上传到我的VPS(centos 6 64位)时遇到了一些麻烦。我正在使用的FTP称为Pure-FTPD,我正在尝试使用Java上传图像。我得到的错误代码是

  

java.net.MalformedURLException:对于输入字符串:“ VPS PASS HERE @ 9X.XXX.2XX.X8”       在java.net.URL。(未知来源)       在java.net.URL。(未知来源)       在java.net.URL。(未知来源)       在FtpUrlUpload.main(FtpUrlUpload.java:25)   引起:java.lang.NumberFormatException:对于输入字符串:“ VPS PASS HERE @ 9X.XXX.2XX.X8”       at java.lang.NumberFormatException.forInputString(Unknown Source)       在java.lang.Integer.parseInt(未知来源)       在java.lang.Integer.parseInt(未知来源)       在java.net.URLStreamHandler.parseURL(未知来源)       ......还有4个

这是我的完整代码。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class FtpUrlUpload {

private static final int BUFFER_SIZE = 4096;

public static void main(String[] args) {
    String ftpUrl = "ftp://%s:%s@%s/%s;type=i";
    String host = "9X.XXX.2XX.X8";
    String user = "VPS USERNAME HERE";
    String pass = "VPS PASS HERE";
    String filePath = "C:\\Users\\user\\desktop\\Untitled.png";
    String uploadPath = "public_html/Untitled.png";

    ftpUrl = String.format(ftpUrl, user, pass, host, uploadPath);
    System.out.println("Upload URL: " + ftpUrl);

    try {
        URL url = new URL(ftpUrl);
        URLConnection conn = url.openConnection();
        OutputStream outputStream = conn.getOutputStream();
        FileInputStream inputStream = new FileInputStream(filePath);

        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        inputStream.close();
        outputStream.close();

        System.out.println("File uploaded");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
}

1 个答案:

答案 0 :(得分:0)

我假设这是由于用户名/密码中的空格未正确编码?

尝试使用URI.toURL()

http://docs.oracle.com/javase/6/docs/api/java/net/URI.html