Reading a remote file using Java

Reading binary file through http and saving it into local file (taken from 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();

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,

    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.


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

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

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

Tags:

Java

File