gpt4 book ai didi

java - 使用 jcifs 读取文件的最简单方法

转载 作者:行者123 更新时间:2023-12-02 08:55:25 25 4
gpt4 key购买 nike

我正在尝试使用外部 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);
}

最佳答案

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());
}

关于java - 使用 jcifs 读取文件的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43487647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com