【问题标题】:How to get path of the file on Server using Java Code?如何使用 Java 代码获取服务器上文件的路径?
【发布时间】:2017-06-07 15:13:12
【问题描述】:

我已在服务器“www.server.com”上上传了一个文件。现在我想通过java代码知道文件在同一台服务器上的路径。有没有具体的方法或流程?我是新手。

public class Test {   
    public static void main(String[] args) {
        test test = new test();
        String server ="www.server.com";
        int port = 21;
        String username = "abc";
        String password = "abc`enter code here`";

        FTPClient ftpclient = new FTPClient();


        try {
            ftpclient.connect(server, port);
            ftpclient.login(username, password);
            ftpclient.enterLocalPassiveMode();
            ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

            File firstLocalFile = new File("D:\\ADF\\Tax Files\\TERData.zip");

            String firstRemoteFile = "TERData.zip";

            InputStream inputstream = new FileInputStream(firstLocalFile);
            System.out.println("Start Uploading the First File");

            System.out.println(" File Path ":+firstLocalFile.getAbsolutePath());

            boolean done = ftpclient.storeFile(firstRemoteFile, inputstream);

            if(done){
                System.out.println(" File successfully uploaded ");
            }                              
        } catch (IOException e) {
            // TODO: Add catch code
            System.out.println("Error: " + e.getMessage());
            e.printStackTrace();
        }

    }
}

【问题讨论】:

  • 你可以试试打印ftpclient.printWorkingDirectory();
  • 我尝试使用它确实打印了我的目录但实际上它不是我需要的目录。
  • 哪个目录打印的???
  • 问题是当我通过端口 22 登录时,我看到了我想要的目录。但是当我通过端口 21 登录时,该目录不存在。但文件存在。上述方法调用当我通过我不想要的端口 21 登录时,给了我文件的目录路径。你能帮我解决这个问题吗
  • 我认为 telnet 使用 22 端口。 21 用于 FTP。

标签: java file server ftp


【解决方案1】:
    FTPClient ftpClient = new FTPClient();
            try {

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

                 FTPFile[] files1 = ftpClient.listFiles("/test");//"/test/test.txt";
String remoteFile1 =files1[0].getName();
                File downloadFile1 = new File("D:/Downloads/test.mp4");
                OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
                boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
                outputStream1.close();

                if (success) {
                    System.out.println("File #1 has been downloaded successfully.");
                }

【讨论】:

  • 通过打印remoteFile1可以得到上传文件在服务器上的路径吗?
  • 不,这是一个例子。如果您看到 ftpclient 返回一个文件对象,因此您也可以获取路径。请探索 ftpfile 对象。我将更新我的答案
猜你喜欢
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 2011-07-14
  • 2017-09-01
  • 1970-01-01
  • 2011-09-20
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多