首页 > 解决方案 > 如何在受用户名和密码保护的远程位置创建和写入 CSV 文件?

问题描述

我必须用一些数据创建并填充一个 CSV 文件,然后将其放入客户端计算机上受用户名和密码保护的远程位置。我正在使用 apache-commonsCSVPrinter来编写文件。计划的作业写入文件,但我似乎无法通过身份验证过程。

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: Could not write to "file:////*PATH*/*TO*/*CSV_FILE*.csv".

现在,我的 .csv 文件路径在开头包含两个反斜杠,因为如果我删除它们,该行将 FileObject fo = VFS.getManager().resolveFile(exportLocation + fileName, opts);产生以下异常:org.apache.commons.vfs2.FileSystemException: Could not find file with URI "*PATH*\*TO*\*CSV_FILE*.csv" because it is a relative path, and no base URI was provided. 自然,这是因为两个反斜杠指向文件夹中的文件而不是 URI。

我现在的问题是:如何保留所需行的反斜杠,并在写入此行中的文件时删除它们:CSVPrinter csvPrinter = new CSVPrinter((Appendable) fileContent.getOutputStream(), CSVFormat.DEFAULT.withDelimiter(';'));

另外,我现在可以看到最后一个异常是由这个引起的:java.io.FileNotFoundException: *PATH*\*TO*\*CSV_FILE*.csv (Access is denied) 这意味着我仍然无法通过身份验证。

标签: javajcifsapache-commons-vfs

解决方案


好吧,我已经放弃了这种方法,所以我尝试使用 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代码有什么问题。


推荐阅读