您好,登錄后才能下訂單哦!
Java中怎么對(duì)接遠(yuǎn)程文件,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
1、配置文件:copyRemoteFile.properties
# src/dao.properties # 這里保存的都是鍵值對(duì)信息 # interface name(no packgage) = implementation class # 注意: #A:【路徑符號(hào)】【必須】是【/】【如:D:/home/publish】 #B:【鍵key=值value】對(duì)【后面】【絕不允許有空格】【如:REMOTE_HOST_IP=172.77.9.77】 # REMOTE_HOST_IP 遠(yuǎn)程機(jī)器IP # LOGIN_ACCOUNT 遠(yuǎn)程機(jī)器登錄名 # LOGIN_PASSWORD 遠(yuǎn)程機(jī)器登錄密碼 # SHARE_DOC_NAME 遠(yuǎn)程機(jī)器共享文件夾名(設(shè)置共享后必須授予讀寫權(quán)限) # sourcePath 本地路徑 # targetPath 目標(biāo)路徑(真實(shí)路徑=共享文件夾路徑+目標(biāo)路徑) REMOTE_HOST_IP=172.77.9.77 LOGIN_ACCOUNT=77 LOGIN_PASSWORD=77 SHARE_DOC_NAME=vfs_home sourcePath=D:/home/publish targetPath=publish
2、導(dǎo)入jar包:jcifs-1.3.16.jar
3、讀取配置文件中key對(duì)應(yīng)的value類:RemoteConfigUtil.java
package com.remote; import java.io.IOException; import java.util.Properties; /** * 讀取配置文件中key對(duì)應(yīng)的value * @author JunjieQin */ public class RemoteConfigUtil { private String REMOTE_HOST_IP; private String LOGIN_ACCOUNT; private String LOGIN_PASSWORD; private String SHARE_DOC_NAME; private String sourcePath; private String targetPath; //無參構(gòu)造方法 public RemoteConfigUtil() { try { // 讀取配置文件 Properties prop = new Properties(); prop.load(this.getClass().getClassLoader().getResourceAsStream("copyRemoteFile.properties")); // 根據(jù) 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 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; } }
4、操作遠(yuǎn)程共享文件夾類: RemoteFileUtil.java
根據(jù)需求選擇相應(yīng)的 Method
package com.remote; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; 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 * Created by: JunjieQin * Checked in by: * Date: 2011-9-6 * Revision: 1.7 * Description:操作遠(yuǎn)程共享文件夾類 * Amendment History * Modified Date:2011-9-16 * Modified By:JunjieQin * Change Description:From local copy files to remote directory * ***********************************************/ public class RemoteFileUtil { private ArrayList filelist = new ArrayList(); RemoteConfigUtil rc = new RemoteConfigUtil(); private String remoteHostIp; //遠(yuǎn)程主機(jī)IP private String account; //登陸賬戶 private String password; //登陸密碼 private String shareDocName; //共享文件夾名稱 /** * 默認(rèn)構(gòu)造函數(shù) */ public RemoteFileUtil(){ this.remoteHostIp = rc.getREMOTE_HOST_IP(); this.account = rc.getLOGIN_ACCOUNT(); this.password = rc.getLOGIN_PASSWORD(); this.shareDocName = rc.getSHARE_DOC_NAME(); } /** * 構(gòu)造函數(shù) * @param remoteHostIp 遠(yuǎn)程主機(jī)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; } /** * 對(duì)遠(yuǎn)程共享文件進(jìn)行讀取所有行 * @param remoteFileName 文件名 說明:參數(shù)為共享目錄下的相對(duì)路徑 * 若遠(yuǎn)程文件的路徑為:shareDoc\test.txt,則參數(shù)為test.txt(其中shareDoc為共享目錄名稱); * 若遠(yuǎn)程文件的路徑為:shareDoc\doc\text.txt,則參數(shù)為doc\text.txt; * @return 文件的所有行 */ public List<String> readFile(String remoteFileName){ SmbFile smbFile = null; BufferedReader reader = null; List<String> resultLines = null; //構(gòu)建連接字符串,并取得文件連接 String conStr = null; conStr = "smb://"+account+":"+password+"@"+remoteHostIp+"/"+shareDocName+"/"+remoteFileName; try { smbFile = new SmbFile(conStr); } catch (MalformedURLException e) { e.printStackTrace(); } //創(chuàng)建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(); } //循環(huán)對(duì)文件進(jìn)行讀取 String line; try { line = reader.readLine(); if(line != null && line.length()>0){ resultLines = new ArrayList<String>(); } while (line != null) { resultLines.add(line); line = reader.readLine(); } } catch (IOException e) { e.printStackTrace(); } //返回 return resultLines; } /** * 對(duì)遠(yuǎn)程共享文件進(jìn)行寫入 * @param is 本地文件的輸入流 * @param remoteFileName 遠(yuǎn)程文件名 說明:參數(shù)為共享目錄下的相對(duì)路徑 * 若遠(yuǎn)程文件的路徑為:shareDoc\test.txt,則參數(shù)為test.txt(其中shareDoc為共享目錄名稱); * 若遠(yuǎn)程文件的路徑為:shareDoc\doc\text.txt,則參數(shù)為doc\text.txt; * @return */ public boolean writeFile(InputStream is,String remoteFileName){ SmbFile smbFile = null; OutputStream os = null; byte[] buffer = new byte[1024*8]; //構(gòu)建連接字符串,并取得文件連接 String conStr = null; conStr = "smb://"+account+":"+password+"@"+remoteHostIp+"/"+shareDocName+"/"+remoteFileName; try { smbFile = new SmbFile(conStr); } catch (MalformedURLException e) { e.printStackTrace(); return false; } //獲取遠(yuǎn)程文件輸出流并寫文件到遠(yuǎn)程共享文件夾 try { os = new BufferedOutputStream(new SmbFileOutputStream(smbFile)); while((is.read(buffer))!=-1){ os.write(buffer); } } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 對(duì)遠(yuǎn)程共享文件進(jìn)行寫入重載 * @param localFileName 要寫入的本地文件全名 * @param remoteFileName 遠(yuǎn)程文件名 說明:參數(shù)為共享目錄下的相對(duì)路徑 * 若遠(yuǎn)程文件的路徑為:shareDoc\test.txt,則參數(shù)為test.txt(其中shareDoc為共享目錄名稱); * 若遠(yuǎn)程文件的路徑為:shareDoc\doc\text.txt,則參數(shù)為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; } } /** * 對(duì)遠(yuǎn)程共享文件進(jìn)行寫入重載 * @param localFileName 要寫入的本地文件 * @param remoteFileName 遠(yuǎn)程文件名 說明:參數(shù)為共享目錄下的相對(duì)路徑 * 若遠(yuǎn)程文件的路徑為:shareDoc\test.txt,則參數(shù)為test.txt(其中shareDoc為共享目錄名稱); * 若遠(yuǎn)程文件的路徑為:shareDoc\doc\text.txt,則參數(shù)為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; } } /** * 對(duì)遠(yuǎn)程共享文件所有文件 * @return 所有文件 */ public List<String> getFiles(){ SmbFile smbFile = null; BufferedReader reader = null; List<String> resultLines = new ArrayList(); //構(gòu)建連接字符串,并取得文件連接 String conStr = null; conStr = "smb://"+account+":"+password+"@"+remoteHostIp+"/"+shareDocName+"/"; try { smbFile = new SmbFile(conStr); } catch (MalformedURLException e) { e.printStackTrace(); } //創(chuàng)建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; } /** 在本地為共享計(jì)算機(jī)創(chuàng)建文件夾 * @param remoteUrl 遠(yuǎn)程計(jì)算機(jī)路徑 */ public void smbMkDir(String name) { // 注意使用jcifs-1.3.15.jar的時(shí)候 操作遠(yuǎn)程計(jì)算機(jī)的時(shí)候所有類前面須要增加Smb // 創(chuàng)建一個(gè)遠(yuǎn)程文件對(duì)象 String conStr = "smb://" + account + ":" + password + "@" + remoteHostIp + "/" + shareDocName; SmbFile remoteFile; try { remoteFile = new SmbFile(conStr + "/" + name); if (!remoteFile.exists()) { remoteFile.mkdir();// 創(chuàng)建遠(yuǎn)程文件夾 } } catch (MalformedURLException e) { e.printStackTrace(); } catch (SmbException e) { e.printStackTrace(); } } /** * 刪除文件夾 * @param folderPath 共享文件夾下一個(gè)文件夾名 * @return */ public void delFolder(String folderPath) { //String conStr = "smb://"+LOGIN_ACCOUNT+":"+LOGIN_PASSWORD+"@"+remoteHostIp+"/"+shareDocName; try { delAllFile(folderPath); //刪除完里面所有內(nèi)容 String filePath = folderPath; filePath = filePath.toString(); SmbFile myFilePath = new SmbFile(filePath); myFilePath.delete(); //刪除空文件夾 } catch (Exception e) { String message = ("刪除文件夾操作出錯(cuò)"); System.out.println(message); } } /** * 刪除共享文件夾下一個(gè)文件夾名 * @param path 共享文件夾下一個(gè)文件夾名 * @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; } } /** * 復(fù)制整個(gè)文件夾的內(nèi)容 * @param oldPath 準(zhǔn)備拷貝的目錄 * @param newPath 指定絕對(duì)路徑的新目錄 * @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 = "復(fù)制整個(gè)文件夾內(nèi)容操作出錯(cuò)"; System.out.println(message); } } /** * 復(fù)制文件到遠(yuǎn)程計(jì)算機(jī),如果目標(biāo)路徑不存在則創(chuàng)建,反之不創(chuàng)建 * @param localFileFullName 本地指定文件路徑 * @param targetDir 目標(biāo)路徑 */ public void copyFileToRemoteDir(String localFileFullName, String targetDir) { System.err.println(localFileFullName + "--" + targetDir); RemoteFileUtil rf = new RemoteFileUtil(); InputStream is = null; SmbFile smbFile = null; OutputStream os = null; byte[] buffer = new byte[1024 * 8]; // 構(gòu)建連接字符串,并取得文件連接 String conStr = null; conStr = "smb://" + account + ":" + password + "@" + remoteHostIp + "/" + shareDocName + "/" + targetDir; System.err.println(conStr); SmbFile sf; try { sf = new SmbFile("smb://" + account + ":" + password + "@" + remoteHostIp + "/" + shareDocName + "/" + targetDir); if (!sf.exists()) { // 新建目標(biāo)目錄 sf.mkdirs(); is = new FileInputStream(new File(localFileFullName)); // 獲取遠(yuǎn)程文件輸出流并寫文件到遠(yuǎn)程共享文件夾 os = new BufferedOutputStream(new SmbFileOutputStream(smbFile)); while ((is.read(buffer)) != -1) { os.write(buffer); } } } catch (Exception e) { System.err.println("提示:復(fù)制整個(gè)文件夾內(nèi)容操作出錯(cuò)。"); } File file = new File(localFileFullName); if (file.isFile()) { File sourceFile = file; // 源文件 File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file.getName());// 目標(biāo)文件 String name = file.getName();// 文件名 if (targetDir != null && targetFile != null) { rf.writeFile(sourceFile, "/" + targetDir + "/" + name); // 復(fù)制文件 } else if (targetFile != null) { rf.writeFile(sourceFile, name); // 復(fù)制文件 } } } /** * 循環(huán)獲取文件夾內(nèi)所有匹配的文件 * @param strPath 路徑 * @param subStr 匹配字符 * @return */ public ArrayList refreshFileList(String strPath, String subStr) { 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; } // 測(cè)試從本地復(fù)制文件到遠(yuǎn)程目標(biāo)目錄,測(cè)試已通過 public static void main(String[] args) { RemoteConfigUtil rc = new RemoteConfigUtil(); RemoteFileUtil util = new RemoteFileUtil(); util.copyFileToRemoteDir(rc.getSourcePath(), rc.getTargetPath()); } }
看完上述內(nèi)容,你們掌握J(rèn)ava中怎么對(duì)接遠(yuǎn)程文件的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。