Javascript required
Skip to content Skip to sidebar Skip to footer

How to Read Write File in Java

This page discusses the details of reading, writing, creating, and opening files. There are a wide assortment of file I/O methods to choose from. To help brand sense of the API, the following diagram arranges the file I/O methods by complexity.

Line drawing with file I/O methods arranged from least complex (on the left) to most complex (on the right).
File I/O Methods Arranged from Less Complex to More Complex

On the far left of the diagram are the utility methods readAllBytes, readAllLines, and the write methods, designed for simple, common cases. To the right of those are the methods used to iterate over a stream or lines of text, such every bit newBufferedReader, newBufferedWriter, then newInputStream and newOutputStream. These methods are interoperable with the java.io bundle. To the right of those are the methods for dealing with ByteChannels, SeekableByteChannels, and ByteBuffers, such as the newByteChannel method. Finally, on the far correct are the methods that utilise FileChannel for advanced applications needing file locking or memory-mapped I/O.


Annotation: The methods for creating a new file enable you to specify an optional fix of initial attributes for the file. For example, on a file system that supports the POSIX set of standards (such equally UNIX), you tin can specify a file possessor, group possessor, 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 Parameter
  • Normally Used Methods for Small Files
  • Buffered I/O Methods for Text Files
  • Methods for Unbuffered Streams and Interoperable with java.io APIs
  • Methods for Channels and ByteBuffers
  • Methods for Creating Regular and Temporary Files

The OpenOptions Parameter

Several of the methods in this section accept an optional OpenOptions parameter. This parameter is optional and the API tells you lot what the default behavior is for the method when none is specified.

The following StandardOpenOptions enums are supported:

  • WRITE – Opens the file for write access.
  • APPEND – Appends the new information to the finish of the file. This pick is used with the WRITE or CREATE options.
  • TRUNCATE_EXISTING – Truncates the file to goose egg bytes. This selection is used with the WRITE option.
  • CREATE_NEW – Creates a new file and throws an exception if the file already exists.
  • CREATE – Opens the file if it exists or creates a new file if it does non.
  • DELETE_ON_CLOSE – Deletes the file when the stream is airtight. This selection is useful for temporary files.
  • SPARSE – Hints that a newly created file volition be sparse. This avant-garde selection is honored on some file systems, such equally NTFS, where large files with data "gaps" can be stored in a more than efficient style where those empty gaps exercise not consume disk infinite.
  • SYNC – Keeps the file (both content and metadata) synchronized with the underlying storage device.
  • DSYNC – Keeps the file content synchronized with the underlying storage device.

Normally Used Methods for Small Files

Reading All Bytes or Lines from a File

If you accept a small-ish file and you would like to read its unabridged contents in i pass, you can utilise the readAllBytes(Path) or readAllLines(Path, Charset) method. These methods take intendance of most of the piece of work for you, such as opening and endmost the stream, merely are not intended for treatment big files. The following lawmaking shows how to use the readAllBytes method:

Path file = ...; byte[] fileArray; fileArray = Files.readAllBytes(file);          

Writing All Bytes or Lines to a File

You lot tin can use 1 of the write methods to write bytes, or lines, to a file.

  • write(Path, byte[], OpenOption...)
  • write(Path, Iterable< extends CharSequence>, Charset, OpenOption...)

The following code snippet shows how to utilise a write method.

Path file = ...; byte[] buf = ...; Files.write(file, buf);          

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 clogging stream I/O.

Reading a File past 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 style.

The following code snippet shows how to use the newBufferedReader method to read from a file. The file is encoded in "US-ASCII."

Charset charset = Charset.forName("US-ASCII"); try (BufferedReader reader = Files.newBufferedReader(file, charset)) {     String line = nothing;     while ((line = reader.readLine()) != cypher) {         System.out.println(line);     } } catch (IOException x) {     Organisation.err.format("IOException: %s%n", x); }          

Writing a File by Using Buffered Stream I/O

Yous tin can use the newBufferedWriter(Path, Charset, OpenOption...) method to write to a file using a BufferedWriter.

The following code snippet shows how to create a file encoded in "US-ASCII" using this method:

Charset charset = Charset.forName("Usa-ASCII"); String south = ...; endeavor (BufferedWriter author = Files.newBufferedWriter(file, charset)) {     writer.write(s, 0, southward.length()); } grab (IOException ten) {     Organisation.err.format("IOException: %s%northward", x); }          

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.

Path file = ...; endeavor (InputStream in = Files.newInputStream(file);     BufferedReader reader =       new BufferedReader(new InputStreamReader(in))) {     String line = goose egg;     while ((line = reader.readLine()) != null) {         System.out.println(line);     } } grab (IOException 10) {     System.err.println(x); }          

Creating and Writing a File past 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 selection 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.

import static coffee.nio.file.StandardOpenOption.*; import coffee.nio.file.*; import java.io.*;  public grade LogFileTest {    public static void main(String[] args) {      // Convert the string to a     // byte array.     String s = "Hullo Globe! ";     byte data[] = s.getBytes();     Path p = Paths.get("./logfile.txt");      try (OutputStream out = new BufferedOutputStream(       Files.newOutputStream(p, CREATE, Suspend))) {       out.write(data, 0, information.length);     } take hold of (IOException x) {       System.err.println(ten);     }   } }          

Methods for Channels and ByteBuffers

Reading and Writing Files past Using Channel I/O

While stream I/O reads a character at a fourth dimension, 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 besides supports truncating the file associated with the channel and querying the file for its size.

The adequacy to move to different points in the file and then read from or write to that location makes random access of a file possible. Meet Random Admission Files for more data.

There are two methods for reading and writing aqueduct I/O.

  • newByteChannel(Path, OpenOption...)
  • newByteChannel(Path, Set<? extends OpenOption>, FileAttribute<?>...)

Note: The newByteChannel methods return an instance of a SeekableByteChannel. With a default file system, you can bandage this seekable byte channel to a FileChannel providing access to more avant-garde features such mapping a region of the file directly into retentivity for faster access, locking a region of the file then other processes cannot admission it, or reading and writing bytes from an absolute position without affecting the aqueduct'southward electric current position.


Both newByteChannel methods enable you to specify a listing of OpenOption options. The same open up options used by the newOutputStream methods are supported, in improver to i 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, and then the channel is opened for reading.

The following code snippet reads a file and prints information technology to standard output:

public static void readFile(Path path) throws IOException {      // Files.newByteChannel() defaults to StandardOpenOption.READ     attempt (SeekableByteChannel sbc = Files.newByteChannel(path)) {         last int BUFFER_CAPACITY = 10;         ByteBuffer buf = ByteBuffer.classify(BUFFER_CAPACITY);          // Read the bytes with the proper encoding for this platform. If         // you skip this pace, you might see strange or illegible         // characters.         Cord 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 coffee.nio.file.StandardOpenOption.*; import java.nio.*; import coffee.nio.channels.*; import coffee.nio.file.*; import java.nio.file.attribute.*; import java.io.*; import java.util.*;  public grade LogFilePermissionsTest {    public static void master(String[] args) {        // Create the set of options for appending to the file.     Gear up<OpenOption> options = new HashSet<OpenOption>();     options.add(Append);     options.add together(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 south = "Howdy World! ";     byte data[] = southward.getBytes();     ByteBuffer bb = ByteBuffer.wrap(data);          Path file = Paths.go("./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 Files

Creating Files

Y'all can create an empty file with an initial ready of attributes by using the createFile(Path, FileAttribute<?>) method. For example, if, at the time of creation, you lot want a file to have a detail set of file permissions, utilize the createFile method to exercise so. If you exercise 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 post-obit code snippet creates a file with default attributes:

Path file = ...; try {     // Create the empty file with default permissions, etc.     Files.createFile(file); } grab (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: %due south%n", 10); }          

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, every bit described in Creating and Writing a File using Stream I/O. If yous open a new output stream and close it immediately, an empty file is created.

Creating Temporary Files

You lot can create a temporary file using one of the post-obit createTempFile methods:

  • createTempFile(Path, String, String, FileAttribute<?>)
  • createTempFile(String, String, FileAttribute<?>)

The starting time 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 post-obit code snippet gives an case of the 2nd method:

attempt {     Path tempFile = Files.createTempFile(cypher, ".myapp");     System.out.format("The temporary file" +         " has been created: %southward%northward", tempFile) ; } catch (IOException x) {     Organisation.err.format("IOException: %s%n", x); }          

The result of running this file would be something like the post-obit:

The temporary file has been created: /tmp/509668702974537184.myapp          

The specific format of the temporary file proper name is platform specific.

agarnoweli.blogspot.com

Source: https://docs.oracle.com/javase/tutorial/essential/io/file.html