使用 Java 读取远程文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1316360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:10:05  来源:igfitidea点击:

Reading a remote file using Java

javafile

提问by vondip

I am looking for an easy way to get files that are situated on a remote server. For this I created a local ftp server on my Windows XP, and now I am trying to give my test applet the following address:

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

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

and of course I receive the following error:

当然,我收到以下错误:

URI scheme is not "file"

URI 方案不是“文件”

I've been trying some other ways to get the file, they don't seem to work. How should I do it? (I am also keen to perform an HTTP request)

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

采纳答案by Eric Anderson

You can't do this out of the box with ftp.

你不能用 ftp 开箱即用地做到这一点。

If your file is on http, you could do something similar to:

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

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

If you want to use a library for doing FTP, you should check out Apache Commons Net

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

回答by serg

Reading binary file through http and saving it into local file (taken from here):

通过 http 读取二进制文件并将其保存到本地文件中(取自此处):

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

回答by ZZ Coder

You are almost there. You need to use URL, instead of URI. Java comes with default URL handler for FTP. For example, you can read the remote file into byte array like this,

你快到了。您需要使用 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();
    }

However, FTP may not be the best protocol to use in an applet. Besides the security restrictions, you will have to deal with connectivity issues since FTP requires multiple ports. Use HTTP if all possible as suggested by others.

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

回答by Joshua

Since you are on Windows, you can set up a network share and access it that way.

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

回答by Gloria Rampur

This worked for me, while trying to bring the file from a remote machine onto my machine.

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

NOTE - These are the parameters passed to the function mentioned in the code below:

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

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

(here you have to give your machine ip address of the remote system, then the path of the text file (testFileUpload.txt) on the remote machine, here C$means C drive of the remote system. Also the ip address starts with \\, but in order to escape the two backslashes we start it \\\\)

(在这里你必须给远程系统的机器的IP地址,然后将文本文件(路径testFileUpload.txt)在远程机器上,在这里C$是指远程系统的C盘,也与IP地址开始\\,但为了逃避我们开始的两个反斜杠\\\\

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

(here this is the path on the local machine at which the file has to be transferred, it will create this new text file - testFileUploadTransferred.txt, with the contents on the remote file - testFileUpload.txtwhich is on the remote system)

(这里是文件必须传输到的本地机器上的路径,它将创建这个新的文本文件 -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();
        }

    }

}

回答by Matthieu

I have coded a Java Remote Fileclient/server objects to access a remote filesystem as if it was local. It works without any authentication (which was the point at that time) but it could be modified to use SSLSocketinstead of standard sockets for authentication.

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

It is veryraw access: no username/password, no "home"/chroot directory.

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

Everything is kept as simple as possible:

一切都尽可能简单:

Server setup

服务器设置

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

Client setup

客户端设置

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

You have access to remote File, InputStreamand OutputStreamthrough the client. It extends java.io.Filefor seamless use in API using Fileto access its metadata (i.e. length(), lastModified(), ...).

您可以访问 remote FileInputStreamOutputStream通过客户端访问。它扩展了java.io.File使用无缝使用APIFile来访问它的元数据(即length()lastModified()...)。

It also uses optional compression for file chunk transfer and programmable MTU, with optimized whole-file retrieval. A CLI is built-in with an FTP-like syntax for end-users.

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

回答by Feng Zhang

I find this very useful: https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html

我发现这非常有用: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();
    }
}