How to create file java
How to create file java
Reading, Writing, and Creating Files
This page discusses the details of reading, writing, creating, and opening files. There are a wide array of file I/O methods to choose from. To help make sense of the API, the following diagram arranges the file I/O methods by complexity.
File I/O Methods Arranged from Less Complex to More Complex
This page has the following topics:
The OpenOptions Parameter
Several of the methods in this section take an optional OpenOptions parameter. This parameter is optional and the API tells you what the default behavior is for the method when none is specified.
The following StandardOpenOptions enums are supported:
Commonly Used Methods for Small Files
Reading All Bytes or Lines from a File
If you have a small-ish file and you would like to read its entire contents in one pass, you can use the readAllBytes(Path) or readAllLines(Path, Charset) method. These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files. The following code shows how to use the readAllBytes method:
Writing All Bytes or Lines to a File
You can use one of the write methods to write bytes, or lines, to a file.
The following code snippet shows how to use a write method.
Buffered I/O Methods for Text Files
The java.nio.file package supports channel I/O, which moves data in buffers, bypassing some of the layers that can bottleneck stream I/O.
Reading a File by Using Buffered Stream I/O
The newBufferedReader(Path, Charset) method opens a file for reading, returning a BufferedReader that can be used to read text from a file in an efficient manner.
The following code snippet shows how to use the newBufferedReader method to read from a file. The file is encoded in «US-ASCII.»
Writing a File by Using Buffered Stream I/O
The following code snippet shows how to create a file encoded in «US-ASCII» using this method:
Methods for Unbuffered Streams and Interoperable with java.io APIs
Reading a File by Using Stream I/O
To open a file for reading, you can use the newInputStream(Path, OpenOption. ) method. This method returns an unbuffered input stream for reading bytes from the file.
Creating and Writing a File by Using Stream I/O
You can create a file, append to a file, or write to a file by using the newOutputStream(Path, OpenOption. ) method. This method opens or creates a file for writing bytes and returns an unbuffered output stream.
The method takes an optional OpenOption parameter. If no open options are specified, and the file does not exist, a new file is created. If the file exists, it is truncated. This option is equivalent to invoking the method with the CREATE and TRUNCATE_EXISTING options.
The following example opens a log file. If the file does not exist, it is created. If the file exists, it is opened for appending.
Methods for Channels and ByteBuffers
Reading and Writing Files by Using Channel I/O
While stream I/O reads a character at a time, channel I/O reads a buffer at a time. The ByteChannel interface provides basic read and write functionality. A SeekableByteChannel is a ByteChannel that has the capability to maintain a position in the channel and to change that position. A SeekableByteChannel also supports truncating the file associated with the channel and querying the file for its size.
The capability to move to different points in the file and then read from or write to that location makes random access of a file possible. See Random Access Files for more information.
There are two methods for reading and writing channel I/O.
Both newByteChannel methods enable you to specify a list of OpenOption options. The same open options used by the newOutputStream methods are supported, in addition to one more option: READ is required because the SeekableByteChannel supports both reading and writing.
Specifying READ opens the channel for reading. Specifying WRITE or APPEND opens the channel for writing. If none of these options are specified, then the channel is opened for reading.
The following code snippet reads a file and prints it to standard output:
The following example, written for UNIX and other POSIX file systems, creates a log file with a specific set of file permissions. This code creates a log file or appends to the log file if it already exists. The log file is created with read/write permissions for owner and read only permissions for group.
Methods for Creating Regular and Temporary Files
Creating Files
You can create an empty file with an initial set of attributes by using the createFile(Path, FileAttribute ) method. For example, if, at the time of creation, you want a file to have a particular set of file permissions, use the createFile method to do so. If you do not specify any attributes, the file is created with default attributes. If the file already exists, createFile throws an exception.
In a single atomic operation, the createFile method checks for the existence of the file and creates that file with the specified attributes, which makes the process more secure against malicious code.
The following code snippet creates a file with default attributes:
POSIX File Permissions has an example that uses createFile(Path, FileAttribute ) to create a file with pre-set permissions.
You can also create a new file by using the newOutputStream methods, as described in Creating and Writing a File using Stream I/O. If you open a new output stream and close it immediately, an empty file is created.
Creating Temporary Files
You can create a temporary file using one of the following createTempFile methods:
The first method allows the code to specify a directory for the temporary file and the second method creates a new file in the default temporary-file directory. Both methods allow you to specify a suffix for the filename and the first method allows you to also specify a prefix. The following code snippet gives an example of the second method:
The result of running this file would be something like the following:
The specific format of the temporary file name is platform specific.
Creating a New File in Java
Last Updated: April 10, 2022
Learn to create a new file using different techniques including NIO Path, IO File, OutputStream, and open-source libraries such as Guava and Apache commons.
1. Create New File using Java NIO
The Files.createFile(path, attribs) is the best way to create a new, empty and writable file in Java and it should be your preferred approach in the future if you are not already using it.
Example 1: Create a new writable file
Example 2: Create a new read-only file
Set the file attributes while creating the file. In the given example, we are setting read-only (“ r “) access for the owner, group, and others using the string “r–r–r–“.
2. Using File.createNewFile()
Use File.createNewFile() method to create a new file if and only if a file with this name does not yet exist. Checking any existing file and creating the file is an atomic operation.
This method returns a boolean value –
3. Using FileOutputStream
The constructor automatically creates a new file in the given location. Note that if a file with a given name already exists, it will be overwritten.
It throws FileNotFoundException if the given file path represents a directory, or a new file cannot be created for any reason.
4. Guava Files.touch()
To include Guava, add the following to pom.xml.
The Files.touch() method is similar to the Unix touch command. It creates an empty file or updates the last updated timestamp
The touch command, when used without any option, creates an empty file assuming the file doesn’t exist. If the file exists it changes the timestamp.
5. Apache Commons IO’s FileUtils
To include Apache Commons IO, add the following to pom.xml.
The FileUtils.touch() is very similar to the previous example. It also implements the same behavior as the “touch” utility on Unix.
Also, as from v1.3 this method creates parent directories if they do not exist. It throws an IOException if the last modified date of the file cannot be set.
Class Files
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
Method Summary
Methods declared in class java.lang.Object
Method Details
newInputStream
The options parameter determines how the file is opened. If no options are present then it is equivalent to opening the file with the READ option. In addition to the READ option, an implementation may also support additional implementation specific options.
newOutputStream
newByteChannel
The options parameter determines how the file is opened. The READ and WRITE options determine if the file should be opened for reading and/or writing. If neither option (or the APPEND option) is present then the file is opened for reading. By default reading or writing commence at the beginning of the file.
An implementation may also support additional implementation specific options.
The attrs parameter is optional file-attributes to set atomically when a new file is created.
newByteChannel
This method opens or creates a file in exactly the manner specified by the newByteChannel method.
newDirectoryStream
When not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.
newDirectoryStream
For example, suppose we want to iterate over the files ending with «.java» in a directory:
The globbing pattern is specified by the getPathMatcher method.
When not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.
newDirectoryStream
When not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.
Where the filter terminates due to an uncaught error or runtime exception then it is propagated to the hasNext or next method. Where an IOException is thrown, it results in the hasNext or next method throwing a DirectoryIteratorException with the IOException as the cause.
Usage Example: Suppose we want to iterate over the files in a directory that are larger than 8K.
createFile
createDirectory
createDirectories
If this method fails, then it may do so after creating some, but not all, of the parent directories.
createTempFile
The details as to how the name of the file is constructed is implementation dependent and therefore not specified. Where possible the prefix and suffix are used to construct candidate names in the same manner as the File.createTempFile(String,String,File) method.
createTempFile
This method works in exactly the manner specified by the createTempFile(Path,String,String,FileAttribute[]) method for the case that the dir parameter is the temporary-file directory.
createTempDirectory
The details as to how the name of the directory is constructed is implementation dependent and therefore not specified. Where possible the prefix is used to construct candidate names.
createTempDirectory
This method works in exactly the manner specified by createTempDirectory(Path,String,FileAttribute[]) method for the case that the dir parameter is the temporary-file directory.
createSymbolicLink
The target parameter is the target of the link. It may be an absolute or relative path and may not exist. When the target is a relative path then file system operations on the resulting link are relative to the path of the link.
createLink
The link parameter locates the directory entry to create. The existing parameter is the path to an existing file. This method creates a new directory entry for the file so that it can be accessed using link as the path. On some file systems this is known as creating a «hard link». Whether the file attributes are maintained for the file or for each directory entry is file system specific and therefore not specified. Typically, a file system requires that all links (directory entries) for a file be on the same file system. Furthermore, on some platforms, the Java virtual machine may require to be started with implementation specific privileges to create hard links or to create links to directories.
delete
An implementation may require to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted.
If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. This method can be used with the walkFileTree method to delete a directory and all entries in the directory, or an entire file-tree where required.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
deleteIfExists
As with the delete(Path) method, an implementation may need to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link, then the symbolic link itself, not the final target of the link, is deleted.
If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file. File attributes are not required to be copied to the target file. If symbolic links are supported, and the file is a symbolic link, then the final target of the link is copied. If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied). This method can be used with the walkFileTree method to copy a directory and all entries in the directory, or an entire file-tree where required.
The options parameter may include any of the following:
Option | Description |
---|---|
REPLACE_EXISTING | If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced. |
COPY_ATTRIBUTES | Attempts to copy the file attributes associated with this file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file stores. Copying of file timestamps may result in precision loss. |
NOFOLLOW_LINKS | Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied. It is implementation specific if file attributes can be copied to the new link. In other words, the COPY_ATTRIBUTES option may be ignored when copying a symbolic link. |
An implementation of this interface may support additional implementation specific options.
Copying a file is not an atomic operation. If an IOException is thrown, then it is possible that the target file is incomplete or some of its file attributes have not been copied from the source file. When the REPLACE_EXISTING option is specified and the target file exists, then the target file is replaced. The check for the existence of the file and the creation of the new file may not be atomic with respect to other file system activities.
Usage Example: Suppose we want to copy a file into a directory, giving it the same file name as the source file:
By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException ). To move a file tree may involve copying rather than moving directories and this can be done using the copy method in conjunction with the Files.walkFileTree utility method.
An implementation of this interface may support additional implementation specific options.
Moving a file will copy the last-modified-time to the target file if supported by both source and target file stores. Copying of file timestamps may result in precision loss. An implementation may also attempt to copy other file attributes but is not required to fail if the file attributes cannot be copied. When the move is performed as a non-atomic operation, and an IOException is thrown, then the state of the files is not defined. The original file and the target file may both exist, the target file may be incomplete or some of its file attributes may not been copied from the original file.
Usage Examples: Suppose we want to rename a file to «newname», keeping the file in the same directory: Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:
readSymbolicLink
getFileStore
isSameFile
mismatch
isHidden
Depending on the implementation this method may require to access the file system to determine if the file is considered hidden.
probeContentType
This method uses the installed FileTypeDetector implementations to probe the given file to determine its content type. Each file type detector’s probeContentType is invoked, in turn, to probe the file type. If the file is recognized then the content type is returned. If the file is not recognized by any of the installed file type detectors then a system-default file type detector is invoked to guess the content type.
The return value of this method is the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined by RFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string is guaranteed to be parsable according to the grammar in the RFC.
getFileAttributeView
A file attribute view provides a read-only or updatable view of a set of file attributes. This method is intended to be used where the file attribute view defines type-safe methods to read or update the file attributes. The type parameter is the type of the attribute view required and the method returns an instance of that type if supported. The BasicFileAttributeView type supports access to the basic attributes of a file. Invoking this method to select a file attribute view of that type will always return an instance of that class.
The options array may be used to indicate how symbolic links are handled by the resulting file attribute view for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed. This option is ignored by implementations that do not support symbolic links.
Usage Example: Suppose we want read or set a file’s ACL, if supported:
readAttributes
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
It is implementation specific if all file attributes are read as an atomic operation with respect to other file system operations.
Usage Example: Suppose we want to read a file’s attributes in bulk: Alternatively, suppose we want to read file’s POSIX attributes without following symbolic links:
setAttribute
The attribute parameter identifies the attribute to be set and takes the form:
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is set. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Usage Example: Suppose we want to set the DOS «hidden» attribute:
getAttribute
The attribute parameter identifies the attribute to be read and takes the form:
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Usage Example: Suppose we require the user ID of the file owner on a system that supports a » unix » view:
readAttributes
The attributes parameter identifies the attributes to be read and takes the form:
The attribute-list component is a comma separated list of one or more names of attributes to read. If the list contains the value «*» then all attributes are read. Attributes that are not supported are ignored and will not be present in the returned map. It is implementation specific if all attributes are read as an atomic operation with respect to other file system operations.
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
getPosixFilePermissions
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
setPosixFilePermissions
getOwner
setOwner
Usage Example: Suppose we want to make «joe» the owner of a file:
isSymbolicLink
Where it is required to distinguish an I/O exception from the case that the file is not a symbolic link then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isSymbolicLink() method.
isDirectory
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Where it is required to distinguish an I/O exception from the case that the file is not a directory then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isDirectory() method.
isRegularFile
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Where it is required to distinguish an I/O exception from the case that the file is not a regular file then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isRegularFile() method.
getLastModifiedTime
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
setLastModifiedTime
Usage Example: Suppose we want to set the last modified time to the current time:
exists
The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Note that the result of this method is immediately outdated. If this method indicates the file exists then there is no guarantee that a subsequent access will succeed. Care should be taken when using this method in security sensitive applications.
notExists
The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
isReadable
Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for reading will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
isWritable
Note that result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for writing will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
isExecutable
Depending on the implementation, this method may require to read file permissions, access control lists, or other file attributes in order to check the effective access to the file. Consequently, this method may not be atomic with respect to other file system operations.
Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to execute the file will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
walkFileTree
Where the file is a directory, and the directory could not be opened, then the visitFileFailed method is invoked with the I/O exception, after which, the file tree walk continues, by default, at the next sibling of the directory.
Where the directory is opened successfully, then the entries in the directory, and their descendants are visited. When all entries have been visited, or an I/O error occurs during iteration of the directory, then the directory is closed and the visitor’s postVisitDirectory method is invoked. The file tree walk then continues, by default, at the next sibling of the directory.
By default, symbolic links are not automatically followed by this method. If the options parameter contains the FOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get the BasicFileAttributes of the link. If they can be read then the visitFile method is invoked with the attributes of the link (otherwise the visitFileFailed method is invoked as specified above).
If a visitor returns a result of null then NullPointerException is thrown.
When a security manager is installed and it denies access to a file (or directory), then it is ignored and the visitor is not invoked for that file (or directory).
walkFileTree
This method works as if invoking it were equivalent to evaluating the expression:
newBufferedReader
The Reader methods that read from the file throw IOException if a malformed or unmappable byte sequence is read.
newBufferedReader
This method works as if invoking it were equivalent to evaluating the expression:
newBufferedWriter
The Writer methods to write text throw IOException if the text cannot be encoded using the specified charset.
newBufferedWriter
This method works as if invoking it were equivalent to evaluating the expression:
By default, the copy fails if the target file already exists or is a symbolic link. If the REPLACE_EXISTING option is specified, and the target file already exists, then it is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link is replaced. In this release, the REPLACE_EXISTING option is the only option required to be supported by this method. Additional options may be supported in future releases.
If an I/O error occurs reading from the input stream or writing to the file, then it may do so after the target file has been created and after some bytes have been read or written. Consequently the input stream may not be at end of stream and may be in an inconsistent state. It is strongly recommended that the input stream be promptly closed if an I/O error occurs.
This method may block indefinitely reading from the input stream (or writing to the file). The behavior for the case that the input stream is asynchronously closed or the thread interrupted during the copy is highly input stream and file system provider specific and therefore not specified.
Usage example: Suppose we want to capture a web page and save it to a file:
If an I/O error occurs reading from the file or writing to the output stream, then it may do so after some bytes have been read or written. Consequently the output stream may be in an inconsistent state. It is strongly recommended that the output stream be promptly closed if an I/O error occurs.
This method may block indefinitely writing to the output stream (or reading from the file). The behavior for the case that the output stream is asynchronously closed or the thread interrupted during the copy is highly output stream and file system provider specific and therefore not specified.
Note that if the given output stream is Flushable then its flush method may need to invoked after this method completes so as to flush any buffered output.
readAllBytes
Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.
readString
readString
This method reads all content including the line separators in the middle and/or at the end. The resulting string will contain line separators as they appear in the file.
readAllLines
Additional Unicode line terminators may be recognized in future releases.
Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. It is not intended for reading in large files.
readAllLines
This method works as if invoking it were equivalent to evaluating the expression:
write
Usage example: By default the method creates a new file or overwrites an existing file. Suppose you instead want to append bytes to an existing file:
write
write
This method works as if invoking it were equivalent to evaluating the expression:
writeString
writeString
All characters are written as they are, including the line separators in the char sequence. No extra characters are added.
The stream is weakly consistent. It is thread safe but does not freeze the directory while iterating, so it may (or may not) reflect updates to the directory that occur after returning from this method.
The returned stream contains a reference to an open directory. The directory is closed by closing the stream.
Operating on a closed stream behaves as if the end of stream has been reached. Due to read-ahead, one or more elements may be returned after the stream has been closed.
If an IOException is thrown when accessing the directory after this method has returned, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.
The stream is weakly consistent. It does not freeze the file tree while iterating, so it may (or may not) reflect updates to the file tree that occur after returned from this method.
By default, symbolic links are not automatically followed by this method. If the options parameter contains the FOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get the BasicFileAttributes of the link.
The maxDepth parameter is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of MAX_VALUE may be used to indicate that all levels should be visited.
When a security manager is installed and it denies access to a file (or directory), then it is ignored and not included in the stream.
The returned stream contains references to one or more open directories. The directories are closed by closing the stream.
If an IOException is thrown when accessing the directory after this method has returned, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.
This method works as if invoking it were equivalent to evaluating the expression:
The returned stream contains references to one or more open directories. The directories are closed by closing the stream.
The returned stream contains references to one or more open directories. The directories are closed by closing the stream.
If an IOException is thrown when accessing the directory after returned from this method, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.
lines
Bytes from the file are decoded into characters using the specified charset and the same line terminators as specified by readAllLines are supported.
The returned stream contains a reference to an open file. The file is closed by closing the stream.
The file contents should not be modified during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.
For line-optimal charsets the stream source’s spliterator has good splitting properties, assuming the file contains a regular sequence of lines. Good splitting properties can result in good parallel stream performance. The spliterator for a line-optimal charset takes advantage of the charset properties (a line feed or a carriage return being efficient identifiable) such that when splitting it can approximately divide the number of covered lines in half.
lines
The returned stream contains a reference to an open file. The file is closed by closing the stream.
The file contents should not be modified during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.
This method works as if invoking it were equivalent to evaluating the expression:
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2022, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
How to create file java
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
Method Summary
Modifier and Type | Method and Description |
---|---|
static long | copy (InputStream in, Path target, CopyOption. options) |
Methods inherited from class java.lang.Object
Method Detail
newInputStream
The options parameter determines how the file is opened. If no options are present then it is equivalent to opening the file with the READ option. In addition to the READ option, an implementation may also support additional implementation specific options.
newOutputStream
newByteChannel
The options parameter determines how the file is opened. The READ and WRITE options determine if the file should be opened for reading and/or writing. If neither option (or the APPEND option) is present then the file is opened for reading. By default reading or writing commence at the beginning of the file.
An implementation may also support additional implementation specific options.
The attrs parameter is optional file-attributes to set atomically when a new file is created.
newByteChannel
This method opens or creates a file in exactly the manner specified by the newByteChannel method.
newDirectoryStream
When not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.
newDirectoryStream
For example, suppose we want to iterate over the files ending with «.java» in a directory:
The globbing pattern is specified by the getPathMatcher method.
When not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.
newDirectoryStream
When not using the try-with-resources construct, then directory stream’s close method should be invoked after iteration is completed so as to free any resources held for the open directory.
Where the filter terminates due to an uncaught error or runtime exception then it is propagated to the hasNext or next method. Where an IOException is thrown, it results in the hasNext or next method throwing a DirectoryIteratorException with the IOException as the cause.
Usage Example: Suppose we want to iterate over the files in a directory that are larger than 8K.
createFile
createDirectory
createDirectories
If this method fails, then it may do so after creating some, but not all, of the parent directories.
createTempFile
The details as to how the name of the file is constructed is implementation dependent and therefore not specified. Where possible the prefix and suffix are used to construct candidate names in the same manner as the File.createTempFile(String,String,File) method.
createTempFile
This method works in exactly the manner specified by the createTempFile(Path,String,String,FileAttribute[]) method for the case that the dir parameter is the temporary-file directory.
createTempDirectory
The details as to how the name of the directory is constructed is implementation dependent and therefore not specified. Where possible the prefix is used to construct candidate names.
createTempDirectory
This method works in exactly the manner specified by createTempDirectory(Path,String,FileAttribute[]) method for the case that the dir parameter is the temporary-file directory.
createSymbolicLink
The target parameter is the target of the link. It may be an absolute or relative path and may not exist. When the target is a relative path then file system operations on the resulting link are relative to the path of the link.
createLink
The link parameter locates the directory entry to create. The existing parameter is the path to an existing file. This method creates a new directory entry for the file so that it can be accessed using link as the path. On some file systems this is known as creating a «hard link». Whether the file attributes are maintained for the file or for each directory entry is file system specific and therefore not specified. Typically, a file system requires that all links (directory entries) for a file be on the same file system. Furthermore, on some platforms, the Java virtual machine may require to be started with implementation specific privileges to create hard links or to create links to directories.
delete
An implementation may require to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted.
If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. This method can be used with the walkFileTree method to delete a directory and all entries in the directory, or an entire file-tree where required.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
deleteIfExists
As with the delete(Path) method, an implementation may need to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link, then the symbolic link itself, not the final target of the link, is deleted.
If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file. File attributes are not required to be copied to the target file. If symbolic links are supported, and the file is a symbolic link, then the final target of the link is copied. If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied). This method can be used with the walkFileTree method to copy a directory and all entries in the directory, or an entire file-tree where required.
The options parameter may include any of the following:
Option | Description |
---|---|
REPLACE_EXISTING | If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced. |
COPY_ATTRIBUTES | Attempts to copy the file attributes associated with this file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file stores. Copying of file timestamps may result in precision loss. |
NOFOLLOW_LINKS | Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied. It is implementation specific if file attributes can be copied to the new link. In other words, the COPY_ATTRIBUTES option may be ignored when copying a symbolic link. |
An implementation of this interface may support additional implementation specific options.
Copying a file is not an atomic operation. If an IOException is thrown, then it is possible that the target file is incomplete or some of its file attributes have not been copied from the source file. When the REPLACE_EXISTING option is specified and the target file exists, then the target file is replaced. The check for the existence of the file and the creation of the new file may not be atomic with respect to other file system activities.
Usage Example: Suppose we want to copy a file into a directory, giving it the same file name as the source file:
By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException ). To move a file tree may involve copying rather than moving directories and this can be done using the copy method in conjunction with the Files.walkFileTree utility method.
An implementation of this interface may support additional implementation specific options.
Moving a file will copy the last-modified-time to the target file if supported by both source and target file stores. Copying of file timestamps may result in precision loss. An implementation may also attempt to copy other file attributes but is not required to fail if the file attributes cannot be copied. When the move is performed as a non-atomic operation, and an IOException is thrown, then the state of the files is not defined. The original file and the target file may both exist, the target file may be incomplete or some of its file attributes may not been copied from the original file.
Usage Examples: Suppose we want to rename a file to «newname», keeping the file in the same directory: Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:
readSymbolicLink
getFileStore
isSameFile
isHidden
Depending on the implementation this method may require to access the file system to determine if the file is considered hidden.
probeContentType
This method uses the installed FileTypeDetector implementations to probe the given file to determine its content type. Each file type detector’s probeContentType is invoked, in turn, to probe the file type. If the file is recognized then the content type is returned. If the file is not recognized by any of the installed file type detectors then a system-default file type detector is invoked to guess the content type.
The return value of this method is the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined by RFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string is guaranteed to be parsable according to the grammar in the RFC.
getFileAttributeView
A file attribute view provides a read-only or updatable view of a set of file attributes. This method is intended to be used where the file attribute view defines type-safe methods to read or update the file attributes. The type parameter is the type of the attribute view required and the method returns an instance of that type if supported. The BasicFileAttributeView type supports access to the basic attributes of a file. Invoking this method to select a file attribute view of that type will always return an instance of that class.
The options array may be used to indicate how symbolic links are handled by the resulting file attribute view for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed. This option is ignored by implementations that do not support symbolic links.
Usage Example: Suppose we want read or set a file’s ACL, if supported:
readAttributes
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
It is implementation specific if all file attributes are read as an atomic operation with respect to other file system operations.
Usage Example: Suppose we want to read a file’s attributes in bulk: Alternatively, suppose we want to read file’s POSIX attributes without following symbolic links:
setAttribute
The attribute parameter identifies the attribute to be set and takes the form:
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is set. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Usage Example: Suppose we want to set the DOS «hidden» attribute:
getAttribute
The attribute parameter identifies the attribute to be read and takes the form:
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Usage Example: Suppose we require the user ID of the file owner on a system that supports a » unix » view:
readAttributes
The attributes parameter identifies the attributes to be read and takes the form:
The attribute-list component is a comma separated list of zero or more names of attributes to read. If the list contains the value «*» then all attributes are read. Attributes that are not supported are ignored and will not be present in the returned map. It is implementation specific if all attributes are read as an atomic operation with respect to other file system operations.
The following examples demonstrate possible values for the attributes parameter:
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
getPosixFilePermissions
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
setPosixFilePermissions
getOwner
setOwner
Usage Example: Suppose we want to make «joe» the owner of a file:
isSymbolicLink
Where it is required to distinguish an I/O exception from the case that the file is not a symbolic link then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isSymbolicLink() method.
isDirectory
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Where it is required to distinguish an I/O exception from the case that the file is not a directory then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isDirectory() method.
isRegularFile
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Where it is required to distinguish an I/O exception from the case that the file is not a regular file then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isRegularFile() method.
getLastModifiedTime
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
setLastModifiedTime
Usage Example: Suppose we want to set the last modified time to the current time:
exists
The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Note that the result of this method is immediately outdated. If this method indicates the file exists then there is no guarantee that a subsequence access will succeed. Care should be taken when using this method in security sensitive applications.
notExists
The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
isReadable
Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for reading will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
isWritable
Note that result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for writing will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
isExecutable
Depending on the implementation, this method may require to read file permissions, access control lists, or other file attributes in order to check the effective access to the file. Consequently, this method may not be atomic with respect to other file system operations.
Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to execute the file will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
walkFileTree
Where the file is a directory, and the directory could not be opened, then the visitFileFailed method is invoked with the I/O exception, after which, the file tree walk continues, by default, at the next sibling of the directory.
Where the directory is opened successfully, then the entries in the directory, and their descendants are visited. When all entries have been visited, or an I/O error occurs during iteration of the directory, then the directory is closed and the visitor’s postVisitDirectory method is invoked. The file tree walk then continues, by default, at the next sibling of the directory.
By default, symbolic links are not automatically followed by this method. If the options parameter contains the FOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get the BasicFileAttributes of the link. If they can be read then the visitFile method is invoked with the attributes of the link (otherwise the visitFileFailed method is invoked as specified above).
If a visitor returns a result of null then NullPointerException is thrown.
When a security manager is installed and it denies access to a file (or directory), then it is ignored and the visitor is not invoked for that file (or directory).
walkFileTree
This method works as if invoking it were equivalent to evaluating the expression:
newBufferedReader
The Reader methods that read from the file throw IOException if a malformed or unmappable byte sequence is read.
newBufferedReader
This method works as if invoking it were equivalent to evaluating the expression:
newBufferedWriter
The Writer methods to write text throw IOException if the text cannot be encoded using the specified charset.
newBufferedWriter
This method works as if invoking it were equivalent to evaluating the expression:
By default, the copy fails if the target file already exists or is a symbolic link. If the REPLACE_EXISTING option is specified, and the target file already exists, then it is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link is replaced. In this release, the REPLACE_EXISTING option is the only option required to be supported by this method. Additional options may be supported in future releases.
If an I/O error occurs reading from the input stream or writing to the file, then it may do so after the target file has been created and after some bytes have been read or written. Consequently the input stream may not be at end of stream and may be in an inconsistent state. It is strongly recommended that the input stream be promptly closed if an I/O error occurs.
This method may block indefinitely reading from the input stream (or writing to the file). The behavior for the case that the input stream is asynchronously closed or the thread interrupted during the copy is highly input stream and file system provider specific and therefore not specified.
Usage example: Suppose we want to capture a web page and save it to a file:
If an I/O error occurs reading from the file or writing to the output stream, then it may do so after some bytes have been read or written. Consequently the output stream may be in an inconsistent state. It is strongly recommended that the output stream be promptly closed if an I/O error occurs.
This method may block indefinitely writing to the output stream (or reading from the file). The behavior for the case that the output stream is asynchronously closed or the thread interrupted during the copy is highly output stream and file system provider specific and therefore not specified.
Note that if the given output stream is Flushable then its flush method may need to invoked after this method completes so as to flush any buffered output.
readAllBytes
Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.
readAllLines
Additional Unicode line terminators may be recognized in future releases.
Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. It is not intended for reading in large files.
readAllLines
This method works as if invoking it were equivalent to evaluating the expression:
write
Usage example: By default the method creates a new file or overwrites an existing file. Suppose you instead want to append bytes to an existing file:
write
write
This method works as if invoking it were equivalent to evaluating the expression:
The stream is weakly consistent. It is thread safe but does not freeze the directory while iterating, so it may (or may not) reflect updates to the directory that occur after returning from this method.
Operating on a closed stream behaves as if the end of stream has been reached. Due to read-ahead, one or more elements may be returned after the stream has been closed.
If an IOException is thrown when accessing the directory after this method has returned, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.
The stream is weakly consistent. It does not freeze the file tree while iterating, so it may (or may not) reflect updates to the file tree that occur after returned from this method.
By default, symbolic links are not automatically followed by this method. If the options parameter contains the FOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get the BasicFileAttributes of the link.
The maxDepth parameter is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of MAX_VALUE may be used to indicate that all levels should be visited.
When a security manager is installed and it denies access to a file (or directory), then it is ignored and not included in the stream.
If an IOException is thrown when accessing the directory after this method has returned, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.
This method works as if invoking it were equivalent to evaluating the expression:
If an IOException is thrown when accessing the directory after returned from this method, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.
lines
Bytes from the file are decoded into characters using the specified charset and the same line terminators as specified by readAllLines are supported.
lines
This method works as if invoking it were equivalent to evaluating the expression:
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2022, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.
How to create file java
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
Method Summary
Modifier and Type | Method | Description | |||||||
---|---|---|---|---|---|---|---|---|---|
static long | copy (InputStream in, Path target, CopyOption. options) |
Option | Description |
---|---|
REPLACE_EXISTING | If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced. |
COPY_ATTRIBUTES | Attempts to copy the file attributes associated with this file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file stores. Copying of file timestamps may result in precision loss. |
NOFOLLOW_LINKS | Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied. It is implementation specific if file attributes can be copied to the new link. In other words, the COPY_ATTRIBUTES option may be ignored when copying a symbolic link. |
An implementation of this interface may support additional implementation specific options.
Copying a file is not an atomic operation. If an IOException is thrown, then it is possible that the target file is incomplete or some of its file attributes have not been copied from the source file. When the REPLACE_EXISTING option is specified and the target file exists, then the target file is replaced. The check for the existence of the file and the creation of the new file may not be atomic with respect to other file system activities.
Usage Example: Suppose we want to copy a file into a directory, giving it the same file name as the source file:
By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same file, in which case this method has no effect. If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved. This method may be invoked to move an empty directory. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. When invoked to move a directory that is not empty then the directory is moved if it does not require moving the entries in the directory. For example, renaming a directory on the same FileStore will usually not require moving the entries in the directory. When moving a directory requires that its entries be moved then this method fails (by throwing an IOException ). To move a file tree may involve copying rather than moving directories and this can be done using the copy method in conjunction with the Files.walkFileTree utility method.
An implementation of this interface may support additional implementation specific options.
Moving a file will copy the last-modified-time to the target file if supported by both source and target file stores. Copying of file timestamps may result in precision loss. An implementation may also attempt to copy other file attributes but is not required to fail if the file attributes cannot be copied. When the move is performed as a non-atomic operation, and an IOException is thrown, then the state of the files is not defined. The original file and the target file may both exist, the target file may be incomplete or some of its file attributes may not been copied from the original file.
Usage Examples: Suppose we want to rename a file to «newname», keeping the file in the same directory: Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:
readSymbolicLink
getFileStore
isSameFile
isHidden
Depending on the implementation this method may require to access the file system to determine if the file is considered hidden.
probeContentType
This method uses the installed FileTypeDetector implementations to probe the given file to determine its content type. Each file type detector’s probeContentType is invoked, in turn, to probe the file type. If the file is recognized then the content type is returned. If the file is not recognized by any of the installed file type detectors then a system-default file type detector is invoked to guess the content type.
The return value of this method is the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined by RFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string is guaranteed to be parsable according to the grammar in the RFC.
getFileAttributeView
A file attribute view provides a read-only or updatable view of a set of file attributes. This method is intended to be used where the file attribute view defines type-safe methods to read or update the file attributes. The type parameter is the type of the attribute view required and the method returns an instance of that type if supported. The BasicFileAttributeView type supports access to the basic attributes of a file. Invoking this method to select a file attribute view of that type will always return an instance of that class.
The options array may be used to indicate how symbolic links are handled by the resulting file attribute view for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed. This option is ignored by implementations that do not support symbolic links.
Usage Example: Suppose we want read or set a file’s ACL, if supported:
readAttributes
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
It is implementation specific if all file attributes are read as an atomic operation with respect to other file system operations.
Usage Example: Suppose we want to read a file’s attributes in bulk: Alternatively, suppose we want to read file’s POSIX attributes without following symbolic links:
setAttribute
The attribute parameter identifies the attribute to be set and takes the form:
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is set. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Usage Example: Suppose we want to set the DOS «hidden» attribute:
getAttribute
The attribute parameter identifies the attribute to be read and takes the form:
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Usage Example: Suppose we require the user ID of the file owner on a system that supports a » unix » view:
readAttributes
The attributes parameter identifies the attributes to be read and takes the form:
The attribute-list component is a comma separated list of one or more names of attributes to read. If the list contains the value «*» then all attributes are read. Attributes that are not supported are ignored and will not be present in the returned map. It is implementation specific if all attributes are read as an atomic operation with respect to other file system operations.
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
getPosixFilePermissions
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
setPosixFilePermissions
getOwner
setOwner
Usage Example: Suppose we want to make «joe» the owner of a file:
isSymbolicLink
Where it is required to distinguish an I/O exception from the case that the file is not a symbolic link then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isSymbolicLink() method.
isDirectory
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Where it is required to distinguish an I/O exception from the case that the file is not a directory then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isDirectory() method.
isRegularFile
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Where it is required to distinguish an I/O exception from the case that the file is not a regular file then the file attributes can be read with the readAttributes method and the file type tested with the BasicFileAttributes.isRegularFile() method.
getLastModifiedTime
The options array may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
setLastModifiedTime
Usage Example: Suppose we want to set the last modified time to the current time:
exists
The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Note that the result of this method is immediately outdated. If this method indicates the file exists then there is no guarantee that a subsequent access will succeed. Care should be taken when using this method in security sensitive applications.
notExists
The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
isReadable
Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for reading will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
isWritable
Note that result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for writing will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
isExecutable
Depending on the implementation, this method may require to read file permissions, access control lists, or other file attributes in order to check the effective access to the file. Consequently, this method may not be atomic with respect to other file system operations.
Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to execute the file will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.
walkFileTree
Where the file is a directory, and the directory could not be opened, then the visitFileFailed method is invoked with the I/O exception, after which, the file tree walk continues, by default, at the next sibling of the directory.
Where the directory is opened successfully, then the entries in the directory, and their descendants are visited. When all entries have been visited, or an I/O error occurs during iteration of the directory, then the directory is closed and the visitor’s postVisitDirectory method is invoked. The file tree walk then continues, by default, at the next sibling of the directory.
By default, symbolic links are not automatically followed by this method. If the options parameter contains the FOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get the BasicFileAttributes of the link. If they can be read then the visitFile method is invoked with the attributes of the link (otherwise the visitFileFailed method is invoked as specified above).
If a visitor returns a result of null then NullPointerException is thrown.
When a security manager is installed and it denies access to a file (or directory), then it is ignored and the visitor is not invoked for that file (or directory).
walkFileTree
This method works as if invoking it were equivalent to evaluating the expression:
newBufferedReader
The Reader methods that read from the file throw IOException if a malformed or unmappable byte sequence is read.
newBufferedReader
This method works as if invoking it were equivalent to evaluating the expression:
newBufferedWriter
The Writer methods to write text throw IOException if the text cannot be encoded using the specified charset.
newBufferedWriter
This method works as if invoking it were equivalent to evaluating the expression:
By default, the copy fails if the target file already exists or is a symbolic link. If the REPLACE_EXISTING option is specified, and the target file already exists, then it is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link is replaced. In this release, the REPLACE_EXISTING option is the only option required to be supported by this method. Additional options may be supported in future releases.
If an I/O error occurs reading from the input stream or writing to the file, then it may do so after the target file has been created and after some bytes have been read or written. Consequently the input stream may not be at end of stream and may be in an inconsistent state. It is strongly recommended that the input stream be promptly closed if an I/O error occurs.
This method may block indefinitely reading from the input stream (or writing to the file). The behavior for the case that the input stream is asynchronously closed or the thread interrupted during the copy is highly input stream and file system provider specific and therefore not specified.
Usage example: Suppose we want to capture a web page and save it to a file:
If an I/O error occurs reading from the file or writing to the output stream, then it may do so after some bytes have been read or written. Consequently the output stream may be in an inconsistent state. It is strongly recommended that the output stream be promptly closed if an I/O error occurs.
This method may block indefinitely writing to the output stream (or reading from the file). The behavior for the case that the output stream is asynchronously closed or the thread interrupted during the copy is highly output stream and file system provider specific and therefore not specified.
Note that if the given output stream is Flushable then its flush method may need to invoked after this method completes so as to flush any buffered output.
readAllBytes
Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.
readString
This method is equivalent to: readString(path, StandardCharsets.UTF_8)
readString
This method reads all content including the line separators in the middle and/or at the end. The resulting string will contain line separators as they appear in the file.
readAllLines
Additional Unicode line terminators may be recognized in future releases.
Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. It is not intended for reading in large files.
readAllLines
This method works as if invoking it were equivalent to evaluating the expression:
write
Usage example: By default the method creates a new file or overwrites an existing file. Suppose you instead want to append bytes to an existing file:
write
write
This method works as if invoking it were equivalent to evaluating the expression:
writeString
This method is equivalent to: writeString(path, test, StandardCharsets.UTF_8, options)
writeString
All characters are written as they are, including the line separators in the char sequence. No extra characters are added.
The stream is weakly consistent. It is thread safe but does not freeze the directory while iterating, so it may (or may not) reflect updates to the directory that occur after returning from this method.
The returned stream contains a reference to an open directory. The directory is closed by closing the stream.
Operating on a closed stream behaves as if the end of stream has been reached. Due to read-ahead, one or more elements may be returned after the stream has been closed.
If an IOException is thrown when accessing the directory after this method has returned, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.
The stream is weakly consistent. It does not freeze the file tree while iterating, so it may (or may not) reflect updates to the file tree that occur after returned from this method.
By default, symbolic links are not automatically followed by this method. If the options parameter contains the FOLLOW_LINKS option then symbolic links are followed. When following links, and the attributes of the target cannot be read, then this method attempts to get the BasicFileAttributes of the link.
The maxDepth parameter is the maximum number of levels of directories to visit. A value of 0 means that only the starting file is visited, unless denied by the security manager. A value of MAX_VALUE may be used to indicate that all levels should be visited.
When a security manager is installed and it denies access to a file (or directory), then it is ignored and not included in the stream.
The returned stream contains references to one or more open directories. The directories are closed by closing the stream.
If an IOException is thrown when accessing the directory after this method has returned, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.
This method works as if invoking it were equivalent to evaluating the expression:
The returned stream contains references to one or more open directories. The directories are closed by closing the stream.
The returned stream contains references to one or more open directories. The directories are closed by closing the stream.
If an IOException is thrown when accessing the directory after returned from this method, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.
lines
Bytes from the file are decoded into characters using the specified charset and the same line terminators as specified by readAllLines are supported.
The returned stream contains a reference to an open file. The file is closed by closing the stream.
The file contents should not be modified during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.
For line-optimal charsets the stream source’s spliterator has good splitting properties, assuming the file contains a regular sequence of lines. Good splitting properties can result in good parallel stream performance. The spliterator for a line-optimal charset takes advantage of the charset properties (a line feed or a carriage return being efficient identifiable) such that when splitting it can approximately divide the number of covered lines in half.
lines
The returned stream contains a reference to an open file. The file is closed by closing the stream.
The file contents should not be modified during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.
This method works as if invoking it were equivalent to evaluating the expression:
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2022, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Источники информации:
- How to create file in linux
- How to create file ubuntu