我必须创建一个 CSV 文件并填充一些数据,然后将其放入客户端计算机上受用户名和密码保护的远程位置。我正在使用 apache-commons CSVPrinter 来写入文件。计划的作业写入文件,但我似乎无法通过身份验证过程。
UserAuthenticator auth = new StaticUserAuthenticator(domain, userName, password);
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile(exportLocation + fileName, opts);
BufferedWriter writer = Files.newBufferedWriter(Paths.get(fo.getURL().getPath()), StandardCharsets.UTF_8);
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withDelimiter(';'));
我收到上面代码的java.nio.file.AccessDeniedException
。谁能告诉我如何解决这个问题,并告诉我我做错了什么?
**************************************************** ***** 编辑 ************************************* ******************
我已将代码更新为:
UserAuthenticator auth = new StaticUserAuthenticator(domain, userName, password);
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile(exportLocation + fileName, opts);
FileContent fileContent = fo.getContent();
CSVPrinter csvPrinter = new CSVPrinter((Appendable) fileContent.getOutputStream(),
CSVFormat.DEFAULT.withDelimiter(';'));
我摆脱了 BufferedWriter
并将其替换为 FileContent
实例。现在我收到org.apache.commons.vfs2.FileSystemException:无法写入“file:////*PATH*/*TO*/*CSV_FILE*.csv”
。
现在,我的 .csv 文件路径在开头包含两个反斜杠,因为如果我删除它们,行 FileObject fo = VFS.getManager().resolveFile(exportLocation + fileName, opts);
将产生以下异常: org.apache.commons.vfs2.FileSystemException: 无法找到 URI 为“*PATH*\*TO*\*CSV_FILE*.csv”的文件,因为它是相对路径,并且没有基路径已提供 URI。
当然,发生这种情况是因为两个反斜杠指向文件夹中的文件而不是 URI。
我现在的问题是:如何保留所需行的反斜杠,并在写入此行中的文件时删除它们:CSVPrinter csvPrinter = new CSVPrinter((Appendable) fileContent.getOutputStream(), CSVFormat .DEFAULT.withDelimiter(';'));
?
另外,我现在可以看到最后一个异常是由以下原因引起的:java.io.FileNotFoundException: *PATH*\*TO*\*CSV_FILE*.csv (访问被拒绝)
这意味着我仍然无法通过身份验证。
最佳答案
好吧,我已经放弃了这种方法,所以我尝试使用 jcifs,并且成功了。
CIFSContext base = SingletonContext.getInstance();
CIFSContext authed1 = base.withCredentials(new NtlmPasswordAuthenticator(domain, userName, password));
SmbFile sFile = new SmbFile("smb://" + exportLocation + fileName, authed1);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
OutputStreamWriter out = new OutputStreamWriter(sfos);
CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT.withDelimiter(';'));
抱歉,我无法弄清楚我的 apache-commons-vfs
代码出了什么问题。
关于java - 如何在受用户名和密码保护的远程位置创建并写入 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60089270/