简体   繁体   中英

Trouble writing to file with SMBJ

Please help. I am unable to create and write to a file using SMBJ. I'm getting this error:

com.hierynomus.mssmb2.SMBApiException: STATUS_OBJECT_NAME_NOT_FOUND (0xc0000034): Create failed for <file path>

Is this a Windows errors or an SMBJ error? Am I using the SMBJ API correctly? I don't understand Windows file attributes/options well.

String fileName ="EricTestFile.txt";
String fileContents = "Mary had a little lamb.";

SMBClient client = new SMBClient();
try (Connection connection = client.connect(serverName)) {
    AuthenticationContext ac = new AuthenticationContext(username, password.toCharArray(), domain);
    Session session = connection.authenticate(ac);

    // Connect to Share
    try (DiskShare share = (DiskShare) session.connectShare(sharename)) {
        for (FileIdBothDirectoryInformation f : share.list(folderName, "*.*")) {
            System.out.println("File : " + f.getFileName());
        }

        //share.openFile(path, accessMask, attributes, shareAccesses, createDisposition, createOptions)
        Set<FileAttributes> fileAttributes = new HashSet<>();
        fileAttributes.add(FileAttributes.FILE_ATTRIBUTE_NORMAL);
        Set<SMB2CreateOptions> createOptions = new HashSet<>();
        createOptions.add(SMB2CreateOptions.FILE_RANDOM_ACCESS);
        File f = share.openFile(folderName+"\\"+fileName, new HashSet(Arrays.asList(new AccessMask[]{AccessMask.GENERIC_ALL})), fileAttributes, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OVERWRITE, createOptions);

        OutputStream oStream = f.getOutputStream();
        oStream.write(fileContents.getBytes());
        oStream.flush();
        oStream.close();
    }
} catch (IOException e) {
    e.printStackTrace();
}

If the file that you're trying to open does not yet exist, you need to use a different SMB2CreateDisposition . You're now using FILE_OVERWRITE , which is documented as:

Overwrite the file if it already exists; otherwise, fail the operation. MUST NOT be used for a printer object.

You probably want to use FILE_OVERWRITE_IF , which does:

Overwrite the file if it already exists; otherwise, create the file. This value SHOULD NOT be used for a printer object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM