RMI远程文件上传实现

public class FileClient {
	public FileClient() {
	}
	public static void main(String[] args) {
		try {
			FileDataService fileDataService = (FileDataService) Naming.lookup("rmi://127.0.0.1:2777/FileDataService");
			fileDataService.upload("/home/build1/file_test/Webos.zip", 
					new FileClient().fileToByte("/home/dev1/file_test/Webos.zip"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//这个方法比较重要,通过这个方法把一个名为filename的文件转化为一个byte数组
	private byte[] fileToByte(String filename){
		byte[] b = null;
		BufferedInputStream is = null;
		try {
			System.out.println("开始>>>>"+System.currentTimeMillis());
			File file = new File(filename);
			b = new byte[(int) file.length()];
			is = new BufferedInputStream(new FileInputStream(file));
			is.read(b);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return b;
	}
}

public interface FileDataService extends Remote{
	//这里的filename应该是该文件存放在服务器端的地址
	public void upload(String filename, byte[] file) throws RemoteException;
}

public class FileDataServiceImp extends UnicastRemoteObject implements FileDataService{
	private static final long serialVersionUID = 1L;

	public FileDataServiceImp() throws RemoteException {
		
	}
	
	@Override
	public void upload(String filename, byte[] fileContent) throws RemoteException{
		File file = new File(filename);
		BufferedOutputStream os = null;
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			
			os = new BufferedOutputStream(new FileOutputStream(file));
			os.write(fileContent);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(os != null) {
				try {
					os.flush();
					os.close();
					System.out.println("结束>>>>"+System.currentTimeMillis());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

public class FileServer {
	FileDataService fileDataService;
	public FileServer() {
		try {
			fileDataService = new FileDataServiceImp();
			LocateRegistry.createRegistry(2777);
			Naming.rebind("rmi://127.0.0.1:2777/FileDataService", fileDataService);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new FileServer();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值