【问题标题】:how to use a supplied username and password to read a file in Java如何使用提供的用户名和密码在 Java 中读取文件
【发布时间】:2010-12-08 00:50:20
【问题描述】:
我需要从 Windows 上运行的 Java 脚本中读取一堆二进制文件。
但是,文件所在的文件夹具有有限的权限。我(即我的 Windows 用户名)有权读取它们,但运行 Java 的用户(这是 Web 应用程序的一部分)没有。如果我在运行时将自己的用户名和 Windows 网络密码传递给 Java,有没有办法使用我自己的权限而不是 Web 用户的权限来读取这些文件?
(请注意,这不会发生在 Web 上;这是在 Web 应用程序的上下文中运行的一次性导入脚本。)
【问题讨论】:
标签:
java
file-io
permissions
【解决方案1】:
您可以创建一个网络共享,然后通过jCIFS 连接
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFileInputStream;
public class Example
{
public static void main(String[] args)
{
SmbFileInputStream fis = null;
try
{
fis = new SmbFileInputStream("smb://DOMAIN;USERNAME:PASSWORD@SERVER/SHARE/filename.txt");
// handle as you would a normal input stream... this example prints the contents of the file
int length;
byte[] buffer = new byte[1024];
while ((length = fis.read(buffer)) != -1)
{
for (int x = 0; x < length; x++)
{
System.out.print((char) buffer[x]);
}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (SmbException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch (Exception ignore)
{
}
}
}
}
}
【解决方案2】:
如果文件位于网络共享上,您可以使用net 工具。与
runtime.exec("net use ...")
打开和关闭共享。我想这应该可行