Java 使用JCIFS訪問網絡文件共享的工具類

gdy8 9年前發布 | 2K 次閱讀 Java

public class UploadDownloadUtil
{

/**
 * 從共享目錄拷貝文件到本地
 * @param remoteUrl 共享目錄上的文件路徑
 * @param localDir 本地目錄
 */
public void smbGet(String remoteUrl, String localDir)
{
    InputStream in = null;
    OutputStream out = null;
    try
    {
        SmbFile remoteFile = new SmbFile(remoteUrl);
        //這一句很重要
        remoteFile.connect();
        if (remoteFile == null)
        {
            System.out.println("共享文件不存在");
            return;
        }
        String fileName = remoteFile.getName();
        File localFile = new File(localDir + File.separator + fileName);
        in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
        out = new BufferedOutputStream(new FileOutputStream(localFile));
        byte[] buffer = new byte[1024];
        while (in.read(buffer) != -1)
        {
            out.write(buffer);
            buffer = new byte[1024];
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            out.close();
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

/**
 * 從本地上傳文件到共享目錄
 * @Version1.0 Sep 25, 2009 3:49:00 PM
 * @param remoteUrl 共享文件目錄
 * @param localFilePath 本地文件絕對路徑
 */
public void smbPut(String remoteUrl, String localFilePath)
{
    InputStream in = null;
    OutputStream out = null;
    try
    {
        File localFile = new File(localFilePath);

        String fileName = localFile.getName();
        SmbFile remoteFile = new SmbFile(remoteUrl + "/" + fileName);
        in = new BufferedInputStream(new FileInputStream(localFile));
        out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
        byte[] buffer = new byte[1024];
        while (in.read(buffer) != -1)
        {
            out.write(buffer);
            buffer = new byte[1024];
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            out.close();
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args)
{
    UploadDownloadUtil test = new UploadDownloadUtil();
    // smb:域名;用戶名:密碼@目的IP/文件夾/文件名.xxx
    // test.smbGet("smb://szpcg;jiang.t:xxx@192.168.193.13/Jake/test.txt",
    // "c://") ;

// test.smbPut("smb://szpcg;jiang.t:xxx@192.168.193.13/Jake", // "c://test.txt");

    //用戶名密碼不能有強字符,也就是不能有特殊字符,否則會被作為分斷處理
    test.smbGet("smb://CHINA;xieruilin:123456Xrl@10.70.36.121/project/report/網上問題智能分析助手使用文檔.doc",
    "c://Temp/");

}

}</pre>

 本文由用戶 gdy8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!