[英]Reading file data from shared folder with authentication (FileNotFound Exception)
以下是我用來通過驗證和讀取文件數據從共享文件夾訪問文件的代碼。(使用JCIF)
public void findFiles() throws Exception{
String url = rs.getString("addPolicyBatchFolder_login_url"); //username, url, password are specified in the property file
String username = rs.getString("addPolicyBatchFolder_login_userName");
String password = rs.getString("addPolicyBatchFolder_login_password");
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
SmbFile dir = null;
dir = new SmbFile(url, auth);
SmbFilenameFilter filter = new SmbFilenameFilter() {
@Override
public boolean accept(SmbFile dir, String name) throws SmbException {
return name.startsWith("starting string of file name");//picking files which has this string on the file name
}
};
for (SmbFile f : dir.listFiles(filter))
{
addPolicyBatch(f.getCanonicalPath()); //passing file path to another method
}
}
使用此代碼,我可以成功進行身份驗證,並且可以列出文件。 而且我嘗試打印規范路徑(我也嘗試僅使用f.path()
)並且無法打印完整路徑。
接下來是下一個方法。
public void addPolicyBatch(String filename) throws Exception{
File csvFile = new File(filename);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(csvFile)); //FileNotFound exception
while((line = br.readLine()) != null){
//more code
在上述方法中,談到bufferReader時,顯示的是FleNotFoundException
。
如果我打印規范路徑,則輸出如下。
smb://sharePath/file.csv
正確的路徑
但是在第二種方法(我得到Exception的地方)中,異常如下。
java.io.FileNotFoundException: smb:\\sharePath\\file.csv (The filename, directory name, or volume label syntax is incorrect)
如您所見, smb:
之后只有一個\\
。
我不確定為什么它沒有傳遞第一種方法中打印的確切文件路徑。
如果您從名稱中刪除前導smb:
則它應該起作用。
另外,您可以按以下方式更改方法,並使用smb文件創建閱讀器:
public void addPolicyBatch(SmbFile smbFile) throws Exception {
BufferedReader br = null;
try {
SmbFileInputStream smbStream = new SmbFileInputStream(smbFile);
br = new BufferedReader(new InputStreamReader(smbStream));
String line;
while((line = br.readLine()) != null){
//....
編輯 ,重命名文件。
如果要使用SmbFile重命名,則需要身份驗證對象
public static void renameSmbFile(SmbFile srcFile, String completeUrl,
NtlmPasswordAuthentication auth) throws Exception {
SmbFile newFile = new SmbFile(completeUrl,auth);
srcFile.renameTo(newFile);
}
Wenn使用File對象,那不是必需的:
public static void renameFile(SmbFile srcFile, String nameWithoutProtocol,
NtlmPasswordAuthentication auth) throws Exception {
String fileName = srcFile.getCanonicalPath();
fileName = fileName.substring(4);//removing smb-protocol
new File(fileName).renameTo(new File(nameWithoutProtocol));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.