使用Java读取远程文件

von*_*dip 19 java file

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

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

当然我收到以下错误:

URI方案不是"文件"

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

Eri*_*son 23

你不能用ftp开箱即用.

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

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

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


ser*_*erg 9

通过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();
Run Code Online (Sandbox Code Playgroud)


ZZ *_*der 5

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

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