【问题标题】:Reading a remote file using Java使用 Java 读取远程文件
【发布时间】:2009-08-22 16:25:35
【问题描述】:

我正在寻找一种简单的方法来获取位于远程服务器上的文件。为此,我在 Windows XP 上创建了一个本地 ftp 服务器,现在我尝试为我的测试小程序提供以下地址:

try
{
    uri = new URI("ftp://localhost/myTest/test.mid");
    File midiFile = new File(uri);
}
catch (Exception ex)
{
}

当然我会收到以下错误:

URI 方案不是“文件”

我一直在尝试其他一些方法来获取文件,但它们似乎不起作用。我该怎么做? (我也热衷于执行 HTTP 请求)

【问题讨论】:

    标签: java file


    【解决方案1】:

    您不能使用 ftp 开箱即用地执行此操作。

    如果您的文件位于 http 上,您可以执行以下操作:

    URL url = new URL("http://q.com/test.mid");
    InputStream is = url.openStream();
    // Read from is
    

    如果你想使用库来做 FTP,你应该看看Apache Commons Net

    【讨论】:

    • 如果我希望将在过去 24 小时内创建的文件从远程服务器复制到本地,有什么建议吗?
    【解决方案2】:

    通过http读取二进制文件并保存到本地文件(取自here):

    URL u = new URL("http://www.java2s.com/binary.dat");
    URLConnection uc = u.openConnection();
    String contentType = uc.getContentType();
    int contentLength = uc.getContentLength();
    if (contentType.startsWith("text/") || contentLength == -1) {
      throw new IOException("This is not a binary file.");
    }
    InputStream raw = uc.getInputStream();
    InputStream in = new BufferedInputStream(raw);
    byte[] data = new byte[contentLength];
    int bytesRead = 0;
    int offset = 0;
    while (offset < contentLength) {
      bytesRead = in.read(data, offset, data.length - offset);
      if (bytesRead == -1)
        break;
      offset += bytesRead;
    }
    in.close();
    
    if (offset != contentLength) {
      throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
    }
    
    String filename = u.getFile().substring(filename.lastIndexOf('/') + 1);
    FileOutputStream out = new FileOutputStream(filename);
    out.write(data);
    out.flush();
    out.close();
    

    【讨论】:

      【解决方案3】:

      你快到了。您需要使用 URL,而不是 URI。 Java 带有用于 FTP 的默认 URL 处理程序。例如,您可以像这样将远程文件读入字节数组,

          try {
              URL url = new URL("ftp://localhost/myTest/test.mid");
              InputStream is = url.openStream();
              ByteArrayOutputStream os = new ByteArrayOutputStream();         
              byte[] buf = new byte[4096];
              int n;          
              while ((n = is.read(buf)) >= 0) 
                  os.write(buf, 0, n);
              os.close();
              is.close();         
              byte[] data = os.toByteArray();
          } catch (MalformedURLException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      

      但是,FTP 可能不是在小程序中使用的最佳协议。除了安全限制之外,您还必须处理连接问题,因为 FTP 需要多个端口。尽可能按照其他人的建议使用 HTTP。

      【讨论】:

        【解决方案4】:

        我觉得这很有用:https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html

        import java.net.*;
        import java.io.*;
        
        public class URLReader {
            public static void main(String[] args) throws Exception {
        
                URL oracle = new URL("http://www.oracle.com/");
                BufferedReader in = new BufferedReader(
                    new InputStreamReader(oracle.openStream()));
        
                String inputLine;
                while ((inputLine = in.readLine()) != null)
                    System.out.println(inputLine);
                in.close();
            }
        }
        

        【讨论】:

          【解决方案5】:

          这对我有用,同时尝试将文件从远程机器带到我的机器上。

          注意 - 这些是传递给下面代码中提到的函数的参数:

          String domain = "xyz.company.com";
          String userName = "GDD";
          String password = "fjsdfks";
          

          (这里你要给你的机器远程系统的ip地址,然后是远程机器上文本文件的路径(testFileUpload.txt),这里C$表示远程系统的C盘。还有ip地址以 \\ 开头,但为了避开两个反斜杠,我们以 \\\\ 开头)

          String remoteFilePathTransfer = "\\\\13.3.2.33\\c$\\FileUploadVerify\\testFileUpload.txt";
          

          (这是本地机器上必须传输文件的路径,它将创建这个新的文本文件 - testFileUploadTransferred.txt,其中包含远程文件 - testFileUpload.txt 上的远程文件系统)

          String fileTransferDestinationTransfer = "D:/FileUploadVerification/TransferredFromRemote/testFileUploadTransferred.txt";
          
          import java.io.File;
          import java.io.IOException;
          
          import org.apache.commons.vfs.FileObject;
          import org.apache.commons.vfs.FileSystemException;
          import org.apache.commons.vfs.FileSystemManager;
          import org.apache.commons.vfs.FileSystemOptions;
          import org.apache.commons.vfs.Selectors;
          import org.apache.commons.vfs.UserAuthenticator;
          import org.apache.commons.vfs.VFS;
          import org.apache.commons.vfs.auth.StaticUserAuthenticator;
          import org.apache.commons.vfs.impl.DefaultFileSystemConfigBuilder;
          
          public class FileTransferUtility {
          
              public void transferFileFromRemote(String domain, String userName, String password, String remoteFileLocation,
                      String fileDestinationLocation) {
          
                  File f = new File(fileDestinationLocation);
                  FileObject destn;
                  try {
                      FileSystemManager fm = VFS.getManager();
          
                      destn = VFS.getManager().resolveFile(f.getAbsolutePath());
          
                      if(!f.exists())
                      {
                          System.out.println("File : "+fileDestinationLocation +" does not exist. transferring file from : "+ remoteFileLocation+" to: "+fileDestinationLocation);
                      }
                      else
                          System.out.println("File : "+fileDestinationLocation +" exists. Transferring(override) file from : "+ remoteFileLocation+" to: "+fileDestinationLocation);
          
                      UserAuthenticator auth = new StaticUserAuthenticator(domain, userName, password);
                      FileSystemOptions opts = new FileSystemOptions();
                      DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
                      FileObject fo = VFS.getManager().resolveFile(remoteFileLocation, opts);
                      System.out.println(fo.exists());
                      destn.copyFrom(fo, Selectors.SELECT_SELF);
                      destn.close();
                      if(f.exists())
                      {
                          System.out.println("File transfer from : "+ remoteFileLocation+" to: "+fileDestinationLocation+" is successful");
                      }
                  }
          
                  catch (FileSystemException e) {
                      e.printStackTrace();
                  }
          
              }
          
          }
          

          【讨论】:

            【解决方案6】:

            我编写了一个Java Remote File 客户端/服务器对象来访问远程文件系统,就好像它是本地的一样。它无需任何身份验证即可工作(这是当时的重点),但可以修改为使用SSLSocket 而不是标准套接字进行身份验证。

            这是非常原始访问:没有用户名/密码,没有“home”/chroot 目录。

            一切都尽可能简单:

            服务器设置

            JRFServer srv = JRFServer.get(new InetSocketAddress(2205));
            srv.start();
            

            客户端设置

            JRFClient cli = new JRFClient(new InetSocketAddress("jrfserver-hostname", 2205));
            

            您可以通过客户端访问远程FileInputStreamOutputStream。它扩展了java.io.File,以便在API 中无缝使用File 来访问其元数据(即length()lastModified()、...)。

            它还使用可选压缩进行文件块传输和可编程 MTU,并优化整个文件检索。为最终用户内置的 CLI 具有类似 FTP 的语法。

            【讨论】:

              【解决方案7】:
              org.apache.commons.io.FileUtils.copyURLToFile(new URL(REMOTE_URL), new File(FILE_NAME), CONNECT_TIMEOUT, READ_TIMEOUT);
              

              【讨论】:

                【解决方案8】:

                由于您使用的是 Windows,因此您可以设置网络共享并以这种方式访问​​它。

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2016-07-13
                  • 2011-05-24
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-05-02
                  • 1970-01-01
                  • 2012-09-18
                  • 2012-07-19
                  相关资源
                  最近更新 更多