java如何遠程訪問一個共享目錄
由于工作需要讀取局域網中一臺機器的 共享目錄中的文件,需要jcifs-1.1.11.jar的支持,使用SMB協議協議,以下是實現了遠程讀取并復制到本地,然后刪除本地文件的功能:
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.Date;
- import jcifs.smb.SmbFile;
- import jcifs.smb.SmbFileInputStream;
- public class TestReadSmb {
- public static void main(String[] args) ...{
- String smbMachine="smb://10.108.23.200/temp/說明文件.txt";
- String localPath="D:/temp";
- File file=readFromSmb(smbMachine,localPath);
- removeFile(file);
- }
- /** ***
- * 從smbMachine讀取文件并存儲到localpath指定的路徑
- *
- * @param smbMachine
- * 共享機器的文件,如smb://xxx:xxx@10.108.23.112/myDocument/測試文本.txt,xxx:xxx是共享機器的用戶名密碼
- * @param localpath
- * 本地路徑
- * @return
- */
- public static File readFromSmb(String smbMachine,String localpath){
- File localfile=null;
- InputStream bis=null;
- OutputStream bos=null;
- try ...{
- SmbFile rmifile = new SmbFile(smbMachine);
- String filename=rmifile.getName();
- bis=new BufferedInputStream(new SmbFileInputStream(rmifile));
- localfile=new File(localpath+File.separator+filename);
- bos=new BufferedOutputStream(new FileOutputStream(localfile));
- int length=rmifile.getContentLength();
- byte[] buffer=new byte[length];
- Date date=new Date();
- bis.read(buffer);
- bos.write(buffer);
- Date end=new Date();
- int time= (int) ((end.getTime()-date.getTime())/1000);
- if(time>0)
- System.out.println("用時:"+time+"秒 "+"速度:"+length/time/1024+"kb/秒");
- } catch (Exception e) ...{
- // TODO Auto-generated catch block
- System.out.println(e.getMessage());
- }finally{
- try {
- bos.close();
- bis.close();
- } catch (IOException e) {
- // // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return localfile;
- }
- public static boolean removeFile(File file) {
- return file.delete();
- }
- }
posted on 2008-12-17 16:52 小卓 閱讀(872) 評論(0) 編輯 收藏 所屬分類: j2se