我正在尝试使用外部jcifs library从网络共享中读取文件。我可以找到的大多数用于读取文件的示例代码非常复杂,可能不必要。我找到了一种简单的方法来写到文件,如下所示。有没有办法用类似的语法读取文件?
SmbFile file= null;
try {
String url = "smb://"+serverAddress+"/"+sharename+"/TEST.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
file = new SmbFile(url, auth);
SmbFileOutputStream out= new SmbFileOutputStream(file);
out.write("test string".getBytes());
out.flush();
out.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "ERROR: "+e);
}
答案 0 :(得分:10)
SmbFile file = null;
byte[] buffer = new byte[1024];
try {
String url = "smb://"+serverAddress+"/"+sharename+"/TEST.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, username, password);
file = new SmbFile(url, auth);
try (SmbFileInputStream in = new SmbFileInputStream(file)) {
int bytesRead = 0;
do {
bytesRead = in.read(buffer)
// here you have "bytesRead" in buffer array
}
while (bytesRead > 0);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "ERROR: "+e);
}
甚至更好,假设你正在处理文本文件 - 使用Java SDK中的BufferedReader
:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new SmbFileInputStream(file)))) {
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
}
}
并写道:
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new SmbFileOutputStream(file)))) {
String toWrite = "xxxxx";
writer.write(toWrite, 0, toWrite.length());
}
答案 1 :(得分:5)
try {
String url = "smb://" + serverAddress + "/" + sharename + "/test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(DOMAIN, USER_NAME, PASSWORD);
String fileContent = IOUtils.toString(new SmbFileInputStream(new SmbFile(url, auth)), StandardCharsets.UTF_8.name());
System.out.println(fileContent);
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
}
答案 2 :(得分:0)
我可以使用以下方法读取一些pdf文件:
private final Singleton<CIFSContext> contextoDdetran = new Singleton<>() {
@Override
public CIFSContext inicializar() {
NtlmPasswordAuthenticator autenticador = new NtlmPasswordAuthenticator(smbDomain, smbUser, smbPassword);
return SingletonContext.getInstance().withCredentials(autenticador);
}
};
public byte[] readSmbFile(String fileName) {
try {
SmbFile file = new SmbFile(fileName, this.contextoDdetran.get());
return file.getInputStream().readAllBytes();
} catch(Exception e) {
final String msgErro = String.format("Error reading file '%s': %s", fileName, e.getMessage());
logger.error(msgErro, e);
throw new IllegalStateException(msgErro);
}
}