使用Java读取远程文件

时间:2009-08-22 16:25:35

标签: java file

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

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

当然我收到以下错误:

  

URI方案不是“文件”

我一直在尝试其他方法来获取文件,但它们似乎无法正常工作。我该怎么办? (我也热衷于执行HTTP请求)

7 个答案:

答案 0 :(得分:21)

你不能用ftp开箱即用。

如果你的文件是http,你可以做类似的事情:

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

如果您想使用库进行FTP,您应该查看Apache Commons Net

答案 1 :(得分:9)

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

答案 2 :(得分:4)

你快到了。您需要使用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可能不是在applet中使用的最佳协议。除了安全限制外,您还必须处理连接问题,因为FTP需要多个端口。如果其他人建议的话,请使用HTTP。

答案 3 :(得分:0)

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

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

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

    }

}

答案 4 :(得分:0)

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

非常原始访问:没有用户名/密码,没有&#34; home&#34; / chroot目录。

一切都尽可能简单:

服务器设置

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

客户端设置

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

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

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

答案 5 :(得分:0)

我觉得这很有用: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();
    }
}

答案 6 :(得分:-5)

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

相关问题