Creating Regular and Temporary Files – Java I/O: Part II

Creating Regular and Temporary Files

The following methods of the Files class can be used to create regular and temporary files, and symbolic links.

Click here to view code image

static Path createFile(Path path, FileAttribute<?>… attrs)
                       throws IOException

Creates an empty file that is denoted by the path parameter, but fails by throwing a FileAlreadyExistsException if the file already exists. It does not create nonexistent parent directories, and throws a NoSuchFileException if any parent directory does not exist.

Click here to view code image

static Path createTempFile(String prefix, String suffix,
                           FileAttribute<?>… attrs) throws IOException
static Path createTempFile(Path dir, String prefix, String suffix,
                           FileAttribute<?>… attrs) throws IOException

Create an empty file in the default temporary-file directory or in the specified directory denoted by the Path object, respectively, using the specified prefix and suffix to generate its name. The default temporary-file directory and naming of temporary files is file-system-specific.

Click here to view code image

static Path createSymbolicLink(Path symbLink, Path target,
                               FileAttribute<?>… attrs) throws IOException

Creates a symbolic link to a target (optional operation). When the target is a relative path then file system operations on the target are relative to the path of the symbolic link. The target of the symbolic link need not exist. Throws a File-AlreadyExistsException if a directory entry with the same name as the symbolic link already exists.

Click here to view code image

static Path readSymbolicLink(Path symbLink) throws IOException

Returns a Path object that denoted the target of a symbolic link (optional operation). The target of the symbolic link need not exist.

For creating files, we will use the following FileAttribute object denoted by the fileAttr reference (p. 1325). It specifies read and write permissions for the owner, but only read access for the group and others.

Click here to view code image

Set<PosixFilePermission> filePerms = PosixFilePermissions.fromString(“rw-r–r–“);
FileAttribute<Set<PosixFilePermission>> fileAttr =
        PosixFilePermissions.asFileAttribute(perms);

Categories: ,

Leave a Reply

Your email address will not be published. Required fields are marked *