0

I want to read a file from a server which is in the different location.

I have an IP, username and password of the server.

How can i read a file in java?

whiterose
  • 4,161
  • 8
  • 23
  • 18
  • It depends what protocol are you going to use. Is this an FTP enabled server? Is this a web server? Anything else? – 01es Jul 07 '11 at 05:36
  • possible duplicate of [Java: What is the best way to SFTP a file from a server](http://stackoverflow.com/questions/14617/java-what-is-the-best-way-to-sftp-a-file-from-a-server) – Suraj Chandran Jul 07 '11 at 05:39

2 Answers2

2
  • You can create a local FTP server and read remote file as byte array something like this

    try {
            URL url = new URL("ftp://localhost/myDir/fileOne.txt");
            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();
         }
    
  • Read the binary file through Http

    URL url = new URL("http://q.com/fileOne.txt");             
    InputStream is = url.openStream();
    
Ronan Boiteau
  • 8,910
  • 6
  • 33
  • 52
Piyush Mattoo
  • 15,520
  • 6
  • 52
  • 59
-1

Rather than use Java, you should just use scp.

If there is a need to do this from Java, you can always form your scp command as a string and pass it to Runtime.getRuntime.exec(). (Be careful with passwords in your source code, though.)

Ray Toal
  • 82,964
  • 16
  • 166
  • 221