java远程windows共享目录通过用户名密码读取文件

需要引入的jar包jcifs-1.3.18.jar

public static void main(String[] args) throws Exception {
String user = "共享windows的用户名";
String pass = "共享windows的密码";
我的共享目录为//100.100.11.19//myshare//file//test.txt

String path = "smb://100.100.11.19//myshare//file//test.txt";

String res=getShareFileContent(user,pass,path);
System.out.println(res);
}

/**
*
* @param username 远程windows用户名
* @param password 远程windows密码
* @param sharePath 共享文件路径
* @return 文件内存
*/
public static String getShareFileContent(String username, String password, String sharePath) {
StringBuilder stringBuilder=new StringBuilder();

SmbFile smbFile = null;
SmbFileInputStream smbfos = null;
InputStreamReader inputStreamReader = null;
BufferedReader br = null;
try {
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", username, password);
smbFile = new SmbFile(sharePath, auth);
smbfos = new SmbFileInputStream(smbFile);
inputStreamReader = new InputStreamReader(smbfos, "utf-8");
br = new BufferedReader(inputStreamReader);
String line = "";
while ((line = br.readLine()) != null) {
stringBuilder.append(line+"\n");
}
} catch (SmbException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {

try {
br.close();
inputStreamReader.close();
smbfos.close();
} catch (IOException e) {
e.printStackTrace();
}

}
return stringBuilder.toString();
}
posted @ 2016-11-03 14:29  救火队员  阅读(2877)  评论(0)    收藏  举报