1

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,391
  • 8
  • 24
  • 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

2 Answers2

3
  • 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
  • 9,608
  • 6
  • 34
  • 56
Piyush Mattoo
  • 15,454
  • 6
  • 47
  • 56
0

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
  • 86,166
  • 18
  • 182
  • 232