Alex Rivera | Logout

Reading a remote file using Java

Asked 2009-08-22T16:25:35.137
22

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:

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"

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)

Edit
Report

2 Answers

6

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.

answered 2009-08-22T22:25:02.447
-7

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

answered 2009-08-22T22:28:17.353

Your Answer