views:

668

answers:

2

can someone help me to find a tutorial or sample java code for

reading file from a any machine which is same network

+1  A: 

The simplest way to do this would be to read it using regular file paths.

On Windows:

new File("\\server\path\to\file.txt")

On Unix:

First mount the share using Samba (SMB, NFS or whatever other protocol) to some location like /mnt/network. Then you can use:

new File("/mnt/network/path/to/file.txt")

Once you have the File object you can use FileInputStream, FileReader or whatever else you want to read the file in.

Edit for comments response. If you are using an Applet, you probably want to pull the file from a web server. You can use the built in java.net.URL class but I would recommend this if you have to do more than just simple stuff: http://hc.apache.org/httpclient-3.x/index.html

Example (from the Commons HTTP Site):

    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}
Chris Dail
in this case do i need to sign applet ?
soField
and i should use shared folder without mounting like ip://folder , do you think java new File("ip//folder/file") is meaningfull
soField
A: 

Try the following url for a tutorial http://www.roseindia.net/java/beginners/construct_file_name_path.shtml

I think the best way is to use java.net.URL to open a InputSteam because you can generalize it to files that are not necessarily on the same network.

Matthew Sowders