java read file from network device
Can someone help me to find a tutorial or sample java code to
read a file from any machine which is in the same network
Solution 1:
The simplest way to do this would be to read it using regular file paths.
On Windows:
new File("\\\\server\\path\\to\\file.txt")
// (double-backslashes required for backslashes in path)
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();
}
}
}