开发者

FTP the file in a specific folder location

Till now I had been using following code to ftp file from one location to another :-

FTPUploader.ja开发者_如何学Gova

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);
        }
    }
}

Now, the problem, the machine where i login with the username/password, open at some fixed location. I am using linux machine for testing. Suppose I login with abc/123456, automatically it takes me to /local/abc location, where i can write a file.

Now I want to FTP the file to another location like /local/abc/folder1, now how to do that, after making some changes in the code above.

Thanks


You'll have to issues ftp change directory commands. I would consider using Apache's FTPClient for this.

  • Apache Commons Net
  • FTPClient JavaDoc


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.");
            }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜