java - 使用 SMBJ 写入文件时遇到问题
问题描述
请帮忙。我无法使用 SMBJ 创建和写入文件。我收到此错误:
com.hierynomus.mssmb2.SMBApiException: STATUS_OBJECT_NAME_NOT_FOUND (0xc0000034): Create failed for <file path>
这是 Windows 错误还是 SMBJ 错误?我是否正确使用了 SMBJ API?我不太了解 Windows 文件属性/选项。
String fileName ="EricTestFile.txt";
String fileContents = "Mary had a little lamb.";
SMBClient client = new SMBClient();
try (Connection connection = client.connect(serverName)) {
AuthenticationContext ac = new AuthenticationContext(username, password.toCharArray(), domain);
Session session = connection.authenticate(ac);
// Connect to Share
try (DiskShare share = (DiskShare) session.connectShare(sharename)) {
for (FileIdBothDirectoryInformation f : share.list(folderName, "*.*")) {
System.out.println("File : " + f.getFileName());
}
//share.openFile(path, accessMask, attributes, shareAccesses, createDisposition, createOptions)
Set<FileAttributes> fileAttributes = new HashSet<>();
fileAttributes.add(FileAttributes.FILE_ATTRIBUTE_NORMAL);
Set<SMB2CreateOptions> createOptions = new HashSet<>();
createOptions.add(SMB2CreateOptions.FILE_RANDOM_ACCESS);
File f = share.openFile(folderName+"\\"+fileName, new HashSet(Arrays.asList(new AccessMask[]{AccessMask.GENERIC_ALL})), fileAttributes, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OVERWRITE, createOptions);
OutputStream oStream = f.getOutputStream();
oStream.write(fileContents.getBytes());
oStream.flush();
oStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
解决方案
如果您尝试打开的文件尚不存在,则需要使用不同的SMB2CreateDisposition
. 您现在正在使用FILE_OVERWRITE
,它被记录为:
如果文件已存在,则覆盖该文件;否则,操作失败。不得用于打印机对象。
您可能想要使用FILE_OVERWRITE_IF
,它可以:
如果文件已存在,则覆盖该文件;否则,创建文件。此值不应用于打印机对象。
推荐阅读
- google-analytics - 分析页面浏览量/事件代码是统计数据的结果
- excel - 如何在Excel中对具有相同值的多个单元格进行分组
- docusignapi - 我有免费的 DocuSign 签名设备开发人员沙盒帐户。但无法使用 DssSign 执行签名操作
- javascript - UTF8 编码脚本未正确编码大写变音字母
- ios - 如何解析嵌套的json?迅速
- xml - 如何将大 XML 文件 (~10GB) 导入 PostgreSQL
- python - 捕获 Scrapy 警告并将其放入项目中
- android - 如何在 MVVM 架构中观察 RecyclerView 适配器中的 LiveData?
- xamarin - Xamarin IOS NFCNdefReaderSession.ReadingAvailable 为假
- android - 如何防止阿拉伯语从右到左对齐?