通常将远程共享目录中进行读取的时候,需要输入登陆的用户和密码,来判断用户是否有权限进行访问,在代码中需要将用户的信息设置进去,来获取该目录的访问权限等;代码如下:
public class CopyNetFileUtil {
private static final Logger logger = Logger.getLogger(CopyNetFileUtil.class);
/**
* sample
* @param inputPath e:/remarks.xls
* @param outputPath /shared/ocean/remarks.xls
* @throws Exception
*/
public static void writeShareFile(String inputPath, String outputPath) throws Exception {
try {
SmbFile smbFile = new SmbFile("smb://用户:密码@IP地址" + outputPath);
File file = new File(inputPath);
int length = (int) file.length(); // get file size
FileInputStream fi = new FileInputStream(file);
byte buffer[] = new byte[2048];
SmbFileOutputStream out = new SmbFileOutputStream(smbFile);
while (fi.read(buffer) != -1) {
out.write(buffer);
}
fi.close();
out.flush();
out.close();
} catch (MalformedURLException e) {
logger.error(e);
throw e;
}
}
public static File readFromSmb(
String userName,
String passWd,
String ip,
String smbFilePath,
String localpath) {
File localfile = null;
InputStream bis = null;
OutputStream bos = null;
String smbMachine = null;
try {
smbMachine = "smb://" + userName + ":" + passWd + "@" + ip + smbFilePath;
SmbFile rmifile = new SmbFile(smbMachine);
String filename = rmifile.getName();
bis = new BufferedInputStream(new SmbFileInputStream(rmifile));
localfile = new File(localpath + filename);
System.out.println("localfile==" + localfile);
bos = new BufferedOutputStream(new FileOutputStream(localfile));
int length = rmifile.getContentLength();
System.out.println("length==" + length);
byte[] buffer = new byte[2048];
while (bis.read(buffer) != -1) {
bos.write(buffer);
}
bos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return localfile;
}
public static void main(String[] args) {
String network_output_ip = "IP地址";
String network_output_id = "用户名";
String network_output_password = "密码";
String network_output_path = "共享文件路径和文件名";
try {
CopyNetFileUtil.writeShareFile("d:/test.txt", network_output_path);
} catch (Exception e) {
e.printStackTrace();
}
}
}