轉自 http://developer.51cto.com/art/201112/308235.htm
我在這裏加了下載方法
RemoteFileUtil.Java爲主要方法
RemoteConfigUtil.Java爲連接共享目錄的配置 可以省略
RemoteFileUtil.Java:
package com.remote;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
/***********************************************
* @File Name: RemoteFileUtil.java
* @Description:操作遠程共享文件夾類
***********************************************/
public class RemoteFileUtil {
private String remoteHostIp; // 遠程主機IP
private String account; // 登陸賬戶
private String password; // 登陸密碼
private String shareDocName; // 共享文件夾名稱
/**
* 默認構造函數
*/
public RemoteFileUtil() {
RemoteConfigUtil rc = new RemoteConfigUtil();
this.remoteHostIp = rc.getREMOTE_HOST_IP();
this.account = rc.getLOGIN_ACCOUNT();
this.password = rc.getLOGIN_PASSWORD();
this.shareDocName = rc.getSHARE_DOC_NAME();
}
/**
* 構造函數
*
* @param remoteHostIp
* 遠程主機Ip
* @param account
* 登陸賬戶
* @param password
* 登陸密碼
* @param sharePath
* 共享文件夾路徑
*/
public RemoteFileUtil(String remoteHostIp, String account, String password,
String shareDocName) {
this.remoteHostIp = remoteHostIp;
this.account = account;
this.password = password;
this.shareDocName = shareDocName;
}
/**
* 對遠程共享文件進行讀取所有行
*
* @param remoteFileName
* 文件名 說明:參數爲共享目錄下的相對路徑
* 若遠程文件的路徑爲:shareDoc\test.txt,則參數爲test.txt(其中shareDoc爲共享目錄名稱);
* 若遠程文件的路徑爲:shareDoc\doc\text.txt,則參數爲doc\text.txt;
* @return 文件的所有行
*/
public List readFile(String remoteFileName) {
SmbFile smbFile = null;
BufferedReader reader = null;
List resultLines = null;
// 構建連接字符串,並取得文件連接
String conStr = null;
conStr = "smb://" + account + ":" + password + "@" + remoteHostIp + "/"
+ shareDocName + "/" + remoteFileName;
try {
smbFile = new SmbFile(conStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// 創建reader
try {
reader = new BufferedReader(new InputStreamReader(
new SmbFileInputStream(smbFile)));
} catch (SmbException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
// 循環對文件進行讀取
String line;
try {
line = reader.readLine();
if (line != null && line.length() > 0) {
resultLines = new ArrayList();
}
while (line != null) {
resultLines.add(line);
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
// 返回
return resultLines;
}
/**
* 對遠程共享文件進行寫入
*
* @param is
* 本地文件的輸入流
* @param remoteFileName
* 遠程文件名 說明:參數爲共享目錄下的相對路徑
* 若遠程文件的路徑爲:shareDoc\test.txt,則參數爲test.txt(其中shareDoc爲共享目錄名稱);
* 若遠程文件的路徑爲:shareDoc\doc\text.txt,則參數爲doc\text.txt;
* @return
*/
public boolean writeFile(InputStream is, String remoteFileName) {
SmbFile smbFile = null;
OutputStream os = null;
byte[] buffer = null;
try {
buffer = new byte[is.available() + 1024];
} catch (IOException e1) {
e1.printStackTrace();
}
// 構建連接字符串,並取得文件連接
String conStr = null;
conStr = "smb://" + account + ":" + password + "@" + remoteHostIp + "/"
+ shareDocName + "/" + remoteFileName;
try {
smbFile = new SmbFile(conStr);
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
}
// 獲取遠程文件輸出流並寫文件到遠程共享文件夾
try {
int byteread = 0;
SmbFileOutputStream smbFileOutputStream = new SmbFileOutputStream(smbFile);
// os = new FileOutputStream();
// while ((byteread = is.read(buffer)) != -1) {
// os.write(buffer, 0, byteread);
// }
while ((byteread = is.read(buffer)) != -1) {
smbFileOutputStream.write(buffer, 0, byteread);
}
/*
* if (oldfile.exists()) { //文件存在時 InputStream inStream = new
* FileInputStream(oldPath); //讀入原文件 FileOutputStream fs = new
* FileOutputStream(newPath); byte[] buffer = new
* byte[inStream.available()]; while ( (byteread =
* inStream.read(buffer)) != -1) { bytesum += byteread; //字節數 文件大小
* System.out.println(bytesum); fs.write(buffer, 0, byteread); }
* inStream.close(); }
*/
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 對遠程共享文件進行寫入重載
*
* @param localFileName
* 要寫入的本地文件全名
* @param remoteFileName
* 遠程文件名 說明:參數爲共享目錄下的相對路徑
* 若遠程文件的路徑爲:shareDoc\test.txt,則參數爲test.txt(其中shareDoc爲共享目錄名稱);
* 若遠程文件的路徑爲:shareDoc\doc\text.txt,則參數爲doc\text.txt;
* @return
*/
public boolean writeFile(String localFileFullName, String remoteFileName) {
try {
return writeFile(new FileInputStream(new File(localFileFullName)),
remoteFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* 對遠程共享文件進行寫入重載
*
* @param localFileName
* 要寫入的本地文件
* @param remoteFileName
* 遠程文件名 說明:參數爲共享目錄下的相對路徑
* 若遠程文件的路徑爲:shareDoc\test.txt,則參數爲test.txt(其中shareDoc爲共享目錄名稱);
* 若遠程文件的路徑爲:shareDoc\doc\text.txt,則參數爲doc\text.txt;
* @return
*/
public boolean writeFile(File localFile, String remoteFileName) {
try {
return writeFile(new FileInputStream(localFile), remoteFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
* 對遠程共享文件所有文件
*
* @return 所有文件
*/
public List getFiles() {
SmbFile smbFile = null;
List resultLines = new ArrayList();
// 構建連接字符串,並取得文件連接
String conStr = null;
conStr = "smb://" + account + ":" + password + "@" + remoteHostIp + "/"
+ shareDocName + "/";
try {
smbFile = new SmbFile(conStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// 創建reader
try {
String[] a = smbFile.list();
for (int i = 0; i < a.length; i++) {
resultLines.add(a[i]);
System.out.println(a[i]);
}
} catch (SmbException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 返回
return resultLines;
}
/**
* 在本地爲共享計算機創建文件夾
*
* @param remoteUrl
* 遠程計算機路徑
*/
public void smbMkDir(String name) {
// 注意使用jcifs-1.3.15.jar的時候 操作遠程計算機的時候所有類前面須要增加Smb
// 創建一個遠程文件對象
String conStr = "smb://" + account + ":" + password + "@"
+ remoteHostIp + "/" + shareDocName;
SmbFile remoteFile;
try {
remoteFile = new SmbFile(conStr + "/" + name);
if (!remoteFile.exists()) {
remoteFile.mkdir();// 創建遠程文件夾
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
}
}
/**
* 刪除文件夾
*
* @param folderPath
* 共享文件夾下一個文件夾名
* @return
*/
public void delFolder(String folderPath) {
// String conStr =
// "smb://"+LOGIN_ACCOUNT+":"+LOGIN_PASSWORD+"@"+remoteHostIp+"/"+shareDocName;
try {
delAllFile(folderPath); // 刪除完裏面所有內容
String filePath = folderPath;
filePath = filePath.toString();
SmbFile myFilePath = new SmbFile(filePath);
myFilePath.delete(); // 刪除空文件夾
} catch (Exception e) {
String message = ("刪除文件夾操作出錯");
System.out.println(message);
}
}
/**
* 刪除共享文件夾下一個文件夾名
*
* @param path
* 共享文件夾下一個文件夾名
* @return
* @return
*/
public boolean delAllFile(String path) {
boolean bea = false;
try {
SmbFile file = new SmbFile(path);
if (!file.exists()) {
return bea;
}
if (!file.isDirectory()) {
return bea;
}
String[] tempList = file.list();
SmbFile temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith("/")) {
temp = new SmbFile(path + tempList[i]);
} else {
temp = new SmbFile(path + "/" + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i] + "/");// 先刪除文件夾裏面的文件
delFolder(path + "/" + tempList[i] + "/");// 再刪除空文件夾
bea = true;
}
}
return bea;
} catch (Exception e) {
return bea;
}
}
/**
* 複製整個文件夾的內容
*
* @param oldPath
* 準備拷貝的目錄
* @param newPath
* 指定絕對路徑的新目錄
* @return
*/
public void copyFolder(String oldPath, String newPath) {
String conStr = "smb://" + account + ":" + password + "@"
+ remoteHostIp + "/" + shareDocName;
System.err.println(conStr);
try {
/**
* 如果存在文件夾刪除文件 SmbFile exittemp = new SmbFile(conStr + "/"+newPath);
* if(exittemp.exists()){ delFolder(conStr+"/"+newPath+"/"); }
*/
SmbFile exittemps = new SmbFile(conStr + "/" + newPath);
if (!exittemps.exists()) {
exittemps.mkdirs(); // 如果文件夾不存在 則建立新文件夾
}
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith("/")) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + "/" + file[i]);
}
if (temp.isFile()) {
if (temp.exists()) {
writeFile(temp, newPath + "/" + file[i]);
}
}
if (temp.isDirectory()) {// 如果是子文件夾
copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
} catch (Exception e) {
String message = "複製整個文件夾內容操作出錯";
System.out.println(message);
e.printStackTrace();
}
}
/**
* 複製文件到遠程計算機,如果目標路徑不存在則創建,反之不創建
*
* @param localFileFullName
* 本地指定文件路徑
* @param targetDir
* 目標路徑
*/
public void copyFileToRemoteDir(String localFileFullName, String targetDir) {
targetDir = targetDir.replace("\\", "/");
System.err.println(localFileFullName + "--" + targetDir);
InputStream is = null;
SmbFile smbFile = null;
OutputStream os = null;
byte[] buffer = new byte[1024 * 8];
// 構建連接字符串,並取得文件連接
String conStr = null;
conStr = "smb://" + account + ":" + password + "@" + remoteHostIp + "/"
+ shareDocName + "/" + targetDir;
System.err.println(conStr);
SmbFile sf;
try {
sf = new SmbFile(conStr);
if (!sf.exists()) {
// 新建目標目錄
sf.mkdirs();
is = new FileInputStream(new File(localFileFullName));
// 獲取遠程文件輸出流並寫文件到遠程共享文件夾
os = new BufferedOutputStream(new SmbFileOutputStream(smbFile));
while ((is.read(buffer)) != -1) {
os.write(buffer);
}
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("提示:複製整個文件夾內容操作出錯。");
}
File file = new File(localFileFullName);
if (file.isFile()) {
File sourceFile = file; // 源文件
File targetFile = new File(new File(targetDir).getAbsolutePath()
+ File.separator + file.getName());// 目標文件
String name = file.getName();// 文件名
if (targetDir != null && targetFile != null) {
writeFile(sourceFile, "/" + targetDir + "/" + name); // 複製文件
} else if (targetFile != null) {
writeFile(sourceFile, name); // 複製文件
}
}
}
/**
* 循環獲取文件夾內所有匹配的文件
*
* @param strPath
* 路徑
* @param subStr
* 匹配字符
* @return
*/
public ArrayList refreshFileList(String strPath, String subStr) {
ArrayList filelist = new ArrayList();
File dir = new File(strPath);
File[] files = dir.listFiles();
if (files == null)
return null;
for (int i = 0; i < files.length; i++) {
if (!files[i].isDirectory()) {
// 應該是絕對路徑
// String strFileName =
// files[i].getAbsolutePath().toLowerCase();
if (files[i].getName().indexOf(subStr) >= 0) {
filelist.add(files[i].getName());
}
}
}
return filelist;
}
/**
* 從共享目錄拷貝文件到本地
*
* @param remoteUrl
* 共享目錄內的文件路徑
* @param localDir
* 本地目錄 文件名不會改變
*/
public void downLoadFile(String remoteUrlFile, String localDir) {
remoteUrlFile = remoteUrlFile.replace("\\", "/");
String conStr = "smb://" + account + ":" + password + "@"
+ remoteHostIp + "/" + shareDocName + "/" + remoteUrlFile;
InputStream in = null;
OutputStream out = null;
try {
SmbFile remoteFile = new SmbFile(conStr);
String fileName = remoteFile.getName();
// fileName.endsWith("")
File localFile = new File(localDir + "/" + fileName);
(new File(localDir)).mkdirs(); // 如果文件夾不存在 則建立新文件夾
in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
out = new FileOutputStream(localFile);
byte[] buffer = new byte[20480];
int len = 0;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
out = null;
}
if (in != null) {
in.close();
in = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 複製遠程共享文件夾內容
*
* @param remoteUrlDirectory
* String 原文件路徑 共離目錄下的子目錄 如:dir/game
* @param localDir
* String 複製後路徑 如:f:/fqf/ff
*/
public void downLoadDirectory(String remoteUrlDirectory, String localDir) {
remoteUrlDirectory = remoteUrlDirectory.replace("\\", "/");
String conStr = "smb://" + account + ":" + password + "@"
+ remoteHostIp + "/" + shareDocName + "/";
InputStream in = null;
OutputStream out = null;
try {
(new File(localDir)).mkdirs(); // 如果文件夾不存在 則建立新文件夾
SmbFile remoteFile = new SmbFile(conStr + remoteUrlDirectory + "/");
String[] fileNameList = remoteFile.list();
SmbFile tempSmb = null;
for (int i = 0; i < fileNameList.length; i++) {
String _fileName = fileNameList[i];
_fileName = _fileName.replace("\\", "/");
// 將路徑
if (remoteUrlDirectory.endsWith("/")) {
tempSmb = new SmbFile(conStr + remoteUrlDirectory
+ _fileName);
} else {
tempSmb = new SmbFile(conStr + remoteUrlDirectory + "/"
+ _fileName);
}
if (tempSmb.isFile()) {
in = new BufferedInputStream(new SmbFileInputStream(
remoteFile + "/" + _fileName));
out = new FileOutputStream(localDir + "/" + _fileName);
byte[] buffer = new byte[20480];
int len = 0;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
}
if (tempSmb.isDirectory()) {
downLoadDirectory(remoteUrlDirectory + "/" + _fileName,
localDir + "/" + _fileName);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
out = null;
}
if (in != null) {
in.close();
in = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 測試從本地複製文件到遠程目標目錄,測試已通過
public static void main(String[] args) {
long startTime = System.currentTimeMillis(); // 獲取開始時間
// 遠程連接配置
// RemoteConfigUtil rc = new RemoteConfigUtil("192.168.3.200","administrator","harmony123;","autoUpdate","C:\\logs","qwe");
RemoteFileUtil util = new RemoteFileUtil("192.168.3.200","administrator", "harmony123;", "autoUpdate");
// RemoteFileUtil util = new RemoteFileUtil("172.16.160.67","administrator", "admin", "testTemp");
// util.copyFileToRemoteDir("D:\\新建文本文檔.txt","");
util.copyFolder("c:\\down", "qwe");
//下載共享目錄下的JDK文件到 c:\\down
// util.downLoadFile("jdk-6u10-rc2-bin-b32-windows-i586-p-12_sep_2008.exe","c:\\down\\");
// 將共享目錄下的qw文件夾裏的內容下載到目錄 c:\\dow
// util.downLoadDirectory("qw", "c:\\down");
long endTime = System.currentTimeMillis(); // 獲取結束時間
System.out.println("程序運行時間: " + (endTime - startTime) + "ms");
}
}
RemoteConfigUtil.Java
package com.remote;
import java.io.IOException;
import java.util.Properties;
/**
* 讀取配置文件中key對應的value
*
* @author JunjieQin
*/
public class RemoteConfigUtil {
/*
* asd
*/
private String REMOTE_HOST_IP;
private String LOGIN_ACCOUNT;
private String LOGIN_PASSWORD;
private String SHARE_DOC_NAME;
private String sourcePath;
private String targetPath;
// 無參構造方法
public RemoteConfigUtil() {
try {
// 讀取配置文件
Properties prop = new Properties();
prop.load(this.getClass().getClassLoader()
.getResourceAsStream("copyRemoteFile.properties"));
// 根據 key 獲取 value
REMOTE_HOST_IP = prop.getProperty("REMOTE_HOST_IP");
LOGIN_ACCOUNT = prop.getProperty("LOGIN_ACCOUNT");
LOGIN_PASSWORD = prop.getProperty("LOGIN_PASSWORD");
SHARE_DOC_NAME = prop.getProperty("SHARE_DOC_NAME");
sourcePath = prop.getProperty("sourcePath");
targetPath = prop.getProperty("targetPath");
} catch (IOException e) {
e.printStackTrace();
}
}
// 參數構造方法
public RemoteConfigUtil(String REMOTE_HOST_IP, String LOGIN_ACCOUNT,
String LOGIN_PASSWORD, String SHARE_DOC_NAME, String sourcePath,
String targetPath) {
// 根據 key 獲取 value
this.REMOTE_HOST_IP = REMOTE_HOST_IP;
this.LOGIN_ACCOUNT = LOGIN_ACCOUNT;
this.LOGIN_PASSWORD = LOGIN_PASSWORD;
this.SHARE_DOC_NAME = SHARE_DOC_NAME;
this.sourcePath = sourcePath;
this.targetPath = targetPath;
}
public String getLOGIN_ACCOUNT() {
return LOGIN_ACCOUNT;
}
public void setLOGIN_ACCOUNT(String login_account) {
LOGIN_ACCOUNT = login_account;
}
public String getLOGIN_PASSWORD() {
return LOGIN_PASSWORD;
}
public void setLOGIN_PASSWORD(String login_password) {
LOGIN_PASSWORD = login_password;
}
public String getREMOTE_HOST_IP() {
return REMOTE_HOST_IP;
}
public void setREMOTE_HOST_IP(String remote_host_ip) {
REMOTE_HOST_IP = remote_host_ip;
}
public String getSHARE_DOC_NAME() {
return SHARE_DOC_NAME;
}
public void setSHARE_DOC_NAME(String share_doc_name) {
SHARE_DOC_NAME = share_doc_name;
}
public String getSourcePath() {
return sourcePath;
}
public void setSourcePath(String sourcePath) {
this.sourcePath = sourcePath;
}
public String getTargetPath() {
return targetPath;
}
public void setTargetPath(String targetPath) {
this.targetPath = targetPath;
}
}
....