使用JCIFS获取远程共享文件
来源:互联网 发布:vps解析域名 编辑:程序博客网 时间:2024/06/05 18:12
- package com.jadyer.util;
-
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
-
- import jcifs.smb.SmbFile;
- import jcifs.smb.SmbFileInputStream;
-
-
-
-
-
-
-
-
-
- public class JCifsUtil {
- public static void main(String[] args) {
- getRemoteFile("jadyer", "myJavaSE", "192.168.8.2/我的测试用例/", "D:/mylocal/");
-
- System.out.println(System.getenv("JAVA_HOME"));
- }
-
-
-
-
-
-
-
-
- private static boolean copyRemoteFile(SmbFile smbFile, String localDirectory) {
- SmbFileInputStream in = null;
- FileOutputStream out = null;
- try {
- File[] localFiles = new File(localDirectory).listFiles();
- if(null == localFiles){
-
-
- new File(localDirectory).mkdirs();
- }else if(localFiles.length > 0){
-
-
-
-
-
- }
- in = new SmbFileInputStream(smbFile);
- out = new FileOutputStream(localDirectory + smbFile.getName());
- byte[] buffer = new byte[1024];
- int len = -1;
- while((len=in.read(buffer)) != -1){
- out.write(buffer, 0, len);
- }
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- } finally {
- if(null != out){
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(null != in){
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return true;
- }
-
-
-
-
-
-
-
-
-
-
- public static boolean getRemoteFile(String remoteUsername, String remotePassword, String remoteFilepath, String localDirectory) {
- boolean isSuccess = false;
- if(remoteFilepath.startsWith("/") || remoteFilepath.startsWith("\\")){
- return isSuccess;
- }
- if(!(localDirectory.endsWith("/") || localDirectory.endsWith("\\"))){
- return isSuccess;
- }
- try {
- SmbFile smbFile = new SmbFile("smb://" + remoteUsername + ":" + remotePassword + "@" + remoteFilepath);
- if(smbFile.isDirectory()){
- for(SmbFile file : smbFile.listFiles()){
- isSuccess = copyRemoteFile(file, localDirectory);
- }
- }else if(smbFile.isFile()){
- isSuccess = copyRemoteFile(smbFile, localDirectory);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return isSuccess;
- }
- }