Reading a remote file using Java

I am looking for an easy way to get files located 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 applets the following address:

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

      

and of course I am getting the following error:

URI scheme is not a file

I tried other ways to get the file, they don't seem to work. How am I supposed to do this? (I also want to make an HTTP request)

+16


source to share


7 replies


You cannot do this out of the box with ftp.

If your file is on http, you can 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 the library for FTP, you should check the Apache Commons Net

+20


source


Reading a binary file over http and saving it to a 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();

      

+8


source


You're almost there. You need to use a URL, not a URI. Java comes with a default FTP URL handler. For example, you can read a remote file into a 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. Aside from security restrictions, you will have to deal with connection issues as FTP requires multiple ports. Use HTTP if possible, as suggested by others.

+4


source


This worked for me trying to dump a file from a remote machine to my machine.

NOTE. These are the parameters passed to the function specified in the code below:

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

      

(here you have to specify your IP address of the device of the remote system, then the path to the text file ( testFileUpload.txt

) on the remote computer, here C$

means drive C for the remote system. Also the ip address starts with \\

, but in order to avoid two backslashes, we start it \\\\

)

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

      

(here is the path on the local machine where the file is to be transferred, it will create this new text file - testFileUploadTransferred.txt

, with the contents of the remote file - testFileUpload.txt

which is on the remote control system)

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

    }

}

      

0


source


I have coded Java Remote File client / server objects to access the remote file system as if it were local. It works without any authentication (which was then at the time), but it could be modified to be used SSLSocket

instead of standard sockets for authentication.

This is very accessible access: no username / password, no "home" / chroot directory.

Everything is as simple as possible:

Server Tuning

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

, InputStream

and OutputStream

through the client. It extends java.io.File

for unhindered use API using File

to access its metadata (ie length()

, lastModified()

...).

It also uses additional compression for file transfers and a programmable MTU with optimized whole file lookups. CLI is built in with FTP-like syntax for end users.

0


source


I find this very useful: 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();
    }
}

      

0


source


Since you are on Windows, you can configure the network share and access it this way.

-five


source







All Articles