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();
}
}