需要导包 jcifs-1.3.14.jar
package com.zhph.hadoop;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
import org.apache.log4j.Logger;
public class RemoteAccessDataTest {
private static Logger logger = Logger.getLogger(RemoteAccessDataTest.class);
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
smbGet("smb://192.168.7.5/share/eventest.txt", "F:/");
// smbPut("smb://hadoop:123456@192.168.7.100/Share", "F:/aa.txt");
}
/**
* 路径格式:smb://192.168.75.204/test/新建 文本文档.txt smb://username:password@192.168.0.77/test
*
* @param remoteUrl 远程路径
* @param localDir 要写入的本地路径
*/
public static void smbGet(String remoteUrl, String localDir) {
System.out.println("进入 smbGet() ....");
InputStream in = null;
OutputStream out = null;
try {
SmbFile remoteFile = new SmbFile(remoteUrl);
System.out.println(remoteFile.exists());
System.out.println(remoteFile.canRead());
System.out.println(remoteFile.canWrite());
System.out.println("尝试连接 远程文件 ....");
if (remoteFile != null && remoteFile.exists()) {
System.out.println("找到文件....");
String fileName = remoteFile.getName();
File localFile = new File(localDir + File.separator + fileName);
in = new BufferedInputStream(new SmbFileInputStream(remoteFile));
// HDFSUtil.uploadFileFromLocation(in, "/TestDir/", "yoyoyoqiekenao.txt");
out = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[1024];
while (in.read(buffer) != -1) {
out.write(buffer);
buffer = new byte[1024];
}
} else {
System.out.println("文件不存在");
// 文件不存在
logger.info(remoteUrl + "文件不存在!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 向共享目录上传文件
*
* @param remoteUrl
* @param localFilePath
*/
public static 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();
out = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} 版权声明:本文为Evennn原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。