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. Show
File I/O Methods Arranged from Less Complex to More Complex On the far left of the diagram are the utility methods Note: The methods for creating a new file enable you to specify an optional set of initial attributes for the file. For example, on a file system that supports the POSIX set of standards (such as UNIX), you can specify a file owner, group owner, or file permissions at the time the file is created. The Managing Metadata page explains file attributes, and how to access and set them. This page has the following topics:
The OpenOptions ParameterSeveral of the methods in this section take an optional The following
Commonly Used Methods for Small FilesReading All Bytes or Lines from a FileIf you have a small-ish file and you would like to read its entire contents in one pass, you can use the Path file = ...; byte[] fileArray; fileArray = Files.readAllBytes(file); Writing All Bytes or Lines to a FileYou can use one of the write methods to write bytes, or lines, to a file.
The following code snippet shows how to use a Path file = ...; byte[] buf = ...; Files.write(file, buf); Buffered I/O Methods for Text FilesThe Reading a File by Using Buffered Stream I/OThe
The following code snippet shows how to use the Charset charset = Charset.forName("US-ASCII"); try (BufferedReader reader = Files.newBufferedReader(file, charset)) { String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException x) { System.err.format("IOException: %s%n", x); } Writing a File by Using Buffered Stream I/OYou can use the The following code snippet shows how to create a file encoded in "US-ASCII" using this method: Charset charset = Charset.forName("US-ASCII"); String s = ...; try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) { writer.write(s, 0, s.length()); } catch (IOException x) { System.err.format("IOException: %s%n", x); } Methods for Unbuffered Streams and Interoperable with java.io APIsReading a File by Using Stream I/OTo open a file for reading, you can use the
Path file = ...; try (InputStream in = Files.newInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException x) { System.err.println(x); } Creating and Writing a File by Using Stream I/OYou can create a file, append to a file, or write to a file by using the The method takes an optional
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. import static java.nio.file.StandardOpenOption.*; import java.nio.file.*; import java.io.*; public class LogFileTest { public static void main(String[] args) { // Convert the string to a // byte array. String s = "Hello World! "; byte data[] = s.getBytes(); Path p = Paths.get("./logfile.txt"); try (OutputStream out = new BufferedOutputStream( Files.newOutputStream(p, CREATE, APPEND))) { out.write(data, 0, data.length); } catch (IOException x) { System.err.println(x); } } } Methods for Channels and ByteBuffersReading and Writing Files by Using Channel I/OWhile stream I/O reads a character at a time, channel I/O reads a buffer at a time. The 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.
Note: The Both Specifying The following code snippet reads a file and prints it to standard output: public static void readFile(Path path) throws IOException { // Files.newByteChannel() defaults to StandardOpenOption.READ try (SeekableByteChannel sbc = Files.newByteChannel(path)) { final int BUFFER_CAPACITY = 10; ByteBuffer buf = ByteBuffer.allocate(BUFFER_CAPACITY); // Read the bytes with the proper encoding for this platform. If // you skip this step, you might see foreign or illegible // characters. String encoding = System.getProperty("file.encoding"); while (sbc.read(buf) > 0) { buf.flip(); System.out.print(Charset.forName(encoding).decode(buf)); buf.clear(); } } } 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. import static java.nio.file.StandardOpenOption.*; import java.nio.*; import java.nio.channels.*; import java.nio.file.*; import java.nio.file.attribute.*; import java.io.*; import java.util.*; public class LogFilePermissionsTest { public static void main(String[] args) { // Create the set of options for appending to the file. Set<OpenOption> options = new HashSet<OpenOption>(); options.add(APPEND); options.add(CREATE); // Create the custom permissions attribute. Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-r-----"); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); // Convert the string to a ByteBuffer. String s = "Hello World! "; byte data[] = s.getBytes(); ByteBuffer bb = ByteBuffer.wrap(data); Path file = Paths.get("./permissions.log"); try (SeekableByteChannel sbc = Files.newByteChannel(file, options, attr)) { sbc.write(bb); } catch (IOException x) { System.out.println("Exception thrown: " + x); } } } Methods for Creating Regular and Temporary FilesCreating FilesYou can create an empty file with an initial set of attributes by using the In a single atomic operation, the The following code snippet creates a file with default attributes: Path file = ...; try { // Create the empty file with default permissions, etc. Files.createFile(file); } catch (FileAlreadyExistsException x) { System.err.format("file named %s" + " already exists%n", file); } catch (IOException x) { // Some other sort of failure, such as permissions. System.err.format("createFile error: %s%n", x); } POSIX File Permissions has an example that uses You can also create a new file by using the Creating Temporary FilesYou can create a temporary file using one of the following
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: try { Path tempFile = Files.createTempFile(null, ".myapp"); System.out.format("The temporary file" + " has been created: %s%n", tempFile) ; } catch (IOException x) { System.err.format("IOException: %s%n", x); } The result of running this file would be something like the following: The temporary file has been created: /tmp/509668702974537184.myapp The specific format of the temporary file name is platform specific. What is a file's read position where is the read position when a file is first opened for reading?The Read position of a file is the location of the next item that will be read from a file. When a file is first opened for reading then by default the read position of the file will begin at the first character of the file.
When an input file is opened what is its read position initially set to?When an input file is opened, its read position is initially set to the first item in the file. When a file that already exists is opened in append mode, the file's existing contents are erased. If you do not handle an exception, it is ignored by the Python interpreter, and the program continues to execute.
What is the term used to describe a file that data is read from?What is the term used to describe a file that data is read from? Input file.
Which type of data file access allows access to any piece of data in the file without reading the data that comes before it?Random access file in C enables us to read or write any data in our disk file without reading or writing every piece of data before it. In a random-access file, we may quickly search for data, edit it or even remove it.
|