将文件FTP到特定文件夹位置

时间:2011-07-06 11:31:28

标签: java url file-transfer

直到现在我一直在使用以下代码将ftp文件从一个位置移到另一个位置: -

FTPUploader.java

public class FTPUploader {

    private URLConnection remoteConnection = null;

    public void connect(String userName, String hostName, String password,
            String remoteFile) {
        try {
            URL url = new URL("ftp://" + userName + ":" + password + "@"
                    + hostName + "/" + remoteFile + ";type=i");
            remoteConnection = url.openConnection();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public void uploadFile(String fileName) {
        try {
            InputStream inputStream = new FileInputStream(fileName);
            BufferedInputStream read = new BufferedInputStream(inputStream);
            OutputStream out = remoteConnection.getOutputStream();
            byte[] buffer = new byte[1024];
            int readCount = 0;
            while ((readCount = read.read(buffer)) > 0) {
                out.write(buffer, 0, readCount);
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

现在,问题是我用用户名/密码登录的机器在某个固定位置打开。我正在使用linux机器进行测试。假设我使用abc / 123456登录,自动将它带到/local/abc位置,我可以在那里写一个文件。

现在我想将文件FTP到/local/abc/folder1之类的其他位置,现在该怎么做,在上面的代码中做了一些更改。

由于

2 个答案:

答案 0 :(得分:4)

您必须发出ftp更改目录命令。我会考虑使用Apache的FTPClient。

答案 1 :(得分:0)

try this after connection with ftp
String hostdir = "/FTP_Folder/remote";
ftp.changeWorkingDirectory(hostdir);
File f1 = new File(localFileFullName);
InputStream input = new FileInputStream(f1);
boolean done = ftp.storeFile(fileName, input);
input.close();
if (done) {
                System.out.println("The first file is uploaded successfully.");
            }