无法在共享驱动器上使用java和smbj读取文件

时间:2017-12-04 12:13:00

标签: java smb

我正在尝试使用SMBJ jar(https://github.com/hierynomus/smbj)从共享驱动器中获取文件。我能够连接到共享磁盘。在连接之后,我执行的任何操作都抛出异常。

对于我的共享驱动器位置://x.x.x.x/containing/folder/filename.txt,我使用的参数为:

//SERVER_ADDRESS = x.x.x.x
//SHARE_NAME = /containing/folder/
//FILE_NAME = filename.txt
//LOCAL_PATH = "D:\\";

    SMBClient client = new SMBClient();
    try (Connection connection = client.connect(SERVER_ADDRESS)) {
        AuthenticationContext ac = new AuthenticationContext(USERNAME, PASSWORD.toCharArray(), DOMAIN);
        Session session = connection.authenticate(ac);
        // Connect to Share
        try (DiskShare share = (DiskShare) session.connectShare(SHARE_NAME)) {
            Set<SMB2ShareAccess> s = new HashSet<>();
            s.add(SMB2ShareAccess.ALL.iterator().next()); // this is to get READ only
            com.hierynomus.smbj.share.File remoteSmbjFile =  share.openFile(SHARE_NAME+FILE_NAME, EnumSet.of(AccessMask.GENERIC_READ), null, s, null, null);
            java.io.File dest = new java.io.File(LOCAL_PATH + FILE_NAME);
            try (InputStream is = remoteSmbjFile.getInputStream();
                    OutputStream os = new FileOutputStream(dest);) {
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("", e);
        return "ERROR";
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("", e);
        return "ERROR";
    }

我得到的例外情况如下。我认为我没有得到正确的参数组合。

com.hierynomus.mssmb2.SMBApiException: STATUS_INVALID_PARAMETER(3221225485/3221225485): Create failed for \containing\folder\
    at com.hierynomus.smbj.share.Share.receive(Share.java:364)
    at com.hierynomus.smbj.share.Share.sendReceive(Share.java:344)
    at com.hierynomus.smbj.share.Share.createFile(Share.java:136)
    at com.hierynomus.smbj.share.DiskShare.open(DiskShare.java:59)
    at com.hierynomus.smbj.share.DiskShare.openDirectory(DiskShare.java:82)
    at com.hierynomus.smbj.share.DiskShare.list(DiskShare.java:169)
    at com.hierynomus.smbj.share.DiskShare.list(DiskShare.java:151)

我无法在这里弄到什么问题。你能否告诉我这里缺少什么。

3 个答案:

答案 0 :(得分:1)

共享名称不应包含\。在您的示例中,它应设置为containing。要打开的文件名应为folder\filename.txt。 另请注意,SMB路径使用\而非/

答案 1 :(得分:0)

如果您的共享文件夹为 \\x.x.x.x\containing\folder\,则 shareName 为 containing

答案 2 :(得分:0)

尝试使用 https://github.com/AgNO3/jcifs-ng 库,如果您的代码中没有必要使用该库。

与 SmbFile 类的共享文件夹的工作连接: SmbException failed to connect hostname/IP_address throwing with proper credentials in Java