无法使用java中的jcifs api从共享驱动器读取文件

时间:2017-08-31 10:26:02

标签: java file smb jcifs

我正在尝试从共享驱动器读取文件但我收到错误

jcifs.smb.SmbException:无法连接到服务器 java.net.UnknownHostException:.. MSBROWSE 。< 01>

我已经厌倦了一些事情,但似乎没有任何工作。我将System.out.println(sFile.canRead())改为true,这意味着连接成功。

public void readFilefromSharedDrive() throws IOException {
        String user = "user" + ":" + "pwd";
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
        SmbFile sFile = null;
        try {
            sFile = new SmbFile("smb:///ip//path//filname.txt", auth);
            System.out.println(sFile.canRead());
            byte[] buffer = new byte[1024];
            try (SmbFileInputStream in = new SmbFileInputStream(sFile)) {
                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);
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
    }

它在SmbFileInputStream中抛出错误=新SmbFileInputStream(sFile)

jcifs.smb.SmbException: Failed to connect to server
java.net.UnknownHostException: ..__MSBROWSE__.<01>
    at jcifs.netbios.NbtAddress.doNameQuery(NbtAddress.java:317)
    at jcifs.netbios.NbtAddress.getByName(NbtAddress.java:422)
    at jcifs.netbios.NbtAddress.getByName(NbtAddress.java:403)
    at jcifs.smb.SmbFile.getFirstAddress(SmbFile.java:845)
    at jcifs.smb.SmbFile.connect(SmbFile.java:946)
    at jcifs.smb.SmbFile.connect0(SmbFile.java:875)
    at jcifs.smb.SmbFile.open0(SmbFile.java:965)
    at jcifs.smb.SmbFile.open(SmbFile.java:999)
    at jcifs.smb.SmbFileInputStream.<init>(SmbFileInputStream.java:73)
    at jcifs.smb.SmbFileInputStream.<init>(SmbFileInputStream.java:65)
    at jcifs.smb.SmbFile.getInputStream(SmbFile.java:2833)
    at java.net.URLConnection.getContent(URLConnection.java:739)
    at 

1 个答案:

答案 0 :(得分:0)

这对我有用

 SmbFile smbfile = getSmbFile(newpath, getCredentials(user, password));

     public NtlmPasswordAuthentication getCredentials(String usr, String pwd) {
    NtlmPasswordAuthentication credentials = null;
    if(usr.length()==0){
        credentials = NtlmPasswordAuthentication.ANONYMOUS;
    }else {
        credentials = new NtlmPasswordAuthentication(null, usr,
                pwd);
    }
    return credentials;
}