JAVA-RMI实现大文件传输

在使用java-rmi的过程中,必然会遇到一个文件上传的问题,由于在rmi中无法传输文件流(比如rmi中的方法参数不能是FileInputStream之类的),那么我们只好选择一种折中的办法,就是先用FileInputStream将文件读到一个Byte数组中,然后把这个Byte数组作为参数传进RMI的方法中,然后在服务器端将Byte数组还原为outputStream,这样就能通过RMI来传输文件了 JAVA-RMI实现大文件传输,具体代码如下:

[代码]FileClient  

package rmiupload;   import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException;   public class FileClient {       public FileClient() {         // TODO Auto-generated constructor stub     }       public static void main(String[] args) {         try {             FileDataService fileDataService = (FileDataService) Naming.lookup("rmi://localhost:9001/FileDataService");             fileDataService.upload("/Users/NeverDie/Documents/test.mp4", new FileClient().fileToByte("/Users/NeverDie/Music/test.mp4"));         } catch (MalformedURLException | RemoteException | NotBoundException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }     } //这个方法比较重要,通过这个方法把一个名为filename的文件转化为一个byte数组     private byte[] fileToByte(String filename){         byte[] b = null;         try {             File file = new File(filename);             b = new byte[(int) file.length()];             BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));             is.read(b);         } catch (FileNotFoundException e) {             // TODO Auto-generated catch block             e.printStackTrace();         } catch (IOException e) {             // TODO Auto-generated catch block             e.printStackTrace();         }         return b;     } }转载请注明来源稳砜诚信在线http://www.wind-fixasia.com

posted on 2013-07-29 11:36  琴深  阅读(508)  评论(0编辑  收藏  举报

导航