Java RMI to download a file
Follow the below steps.
Create FileInterface.java ------------------------ import java.rmi.Remote; import java.rmi.RemoteException; public interface FileInterface extends Remote { public byte[] downloadFile(String fileName) throws RemoteException; } Create FileImpl.java ------------------------ import java.io.*; import java.rmi.*; import java.rmi.server.UnicastRemoteObject; public class FileImpl extends UnicastRemoteObject implements FileInterface { private String name; public FileImpl(String s) throws RemoteException{ super(); name = s; } public byte[] downloadFile(String fileName){ try { File file = new File(fileName); byte buffer[] = new byte[(int)file.length()]; BufferedInputStream input = new BufferedInputStream(new FileInputStream(fileName)); input.read(buffer,0,buffer.length); input.close(); return(buffer); } catch(Exception e){ System.out.println("FileImpl: "+e.getMessage()); e.printStackTrace(); return(null); } } } Create FileClient.java -------------------------- import java.io.*; import java.rmi.*; public class FileClient{ public static void main(String argv[]) { if(argv.length != 2) { System.out.println("Usage: java FileClient fileName servermachineName"); System.exit(0); } try { String name = "//" + argv[1] + "/FileServer"; FileInterface fi = (FileInterface) Naming.lookup(name); byte[] filedata = fi.downloadFile(argv[0]); File file = new File(argv[0]); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file.getName())); output.write(filedata,0,filedata.length); output.flush(); output.close(); } catch(Exception e) { System.err.println("FileServer exception: "+ e.getMessage()); e.printStackTrace(); } } } Create FileServer.java -------------------------- import java.io.*; import java.rmi.*; public class FileServer { public static void main(String argv[]) { if(System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } try { FileInterface fi = new FileImpl("FileServer"); Naming.rebind("rmi://127.0.0.1/FileServer", fi); } catch(Exception e) { System.out.println("FileServer: "+e.getMessage()); e.printStackTrace(); } } } Once after creating above files,inorder to compile and run follow the below stepsOn Server machine
1.compile FileInterface.java and FileImpl.java 2.generate stubs using rmic command ex. rmic FileImpl 3.compile FileServer.java and run FileServer as follows: java -Djava.security.policy=policy.txt FileServerContent of policy.txt
grant { permission java.security.AllPermission "", ""; };On Client machine
1.Compile FileClient.java file. javac FileClient.java java FileClient FileName ServerMachineName
Monday, 16 May 2011
Java RMI code to download the File from the server
Labels:
Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment