Program to Read a File From a Given Location in Java and Print

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 complication.

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 as newBufferedReader, newBufferedWriter, then newInputStream and newOutputStream. These methods are interoperable with the coffee.io package. To the right of those are the methods for dealing with ByteChannels, SeekableByteChannels, and ByteBuffers, such equally the newByteChannel method. Finally, on the far correct are the methods that employ FileChannel for advanced applications needing file locking or memory-mapped I/O.


Note: The methods for creating a new file enable you to specify an optional set of initial attributes for the file. For instance, on a file system that supports the POSIX set up of standards (such as UNIX), you lot 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 gear up them.


This page has the post-obit topics:

  • The OpenOptions Parameter
  • Commonly 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 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:

  • WRITE – Opens the file for write access.
  • Append – Appends the new information to the end of the file. This choice is used with the WRITE or CREATE options.
  • TRUNCATE_EXISTING – Truncates the file to zero bytes. This option is used with the WRITE selection.
  • 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 information technology does non.
  • DELETE_ON_CLOSE – Deletes the file when the stream is closed. This option is useful for temporary files.
  • Sparse – Hints that a newly created file will be sparse. This avant-garde option is honored on some file systems, such as NTFS, where large files with data "gaps" tin can exist stored in a more efficient style where those empty gaps do not swallow 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.

Unremarkably Used Methods for Minor Files

Reading All Bytes or Lines from a File

If you take a small-ish file and you lot would like to read its entire contents in 1 laissez passer, you can use the readAllBytes(Path) or readAllLines(Path, Charset) method. These methods take care of nigh of the work for you, such every bit opening and endmost the stream, but are not intended for handling large files. The following code shows how to apply the readAllBytes method:

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

Writing All Bytes or Lines to a File

Yous tin utilise 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 post-obit lawmaking snippet shows how to use a write method.

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

Buffered I/O Methods for Text Files

The java.nio.file package supports aqueduct I/O, which moves information 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 tin can be used to read text from a file in an efficient mode.

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

Charset charset = Charset.forName("U.s.a.-ASCII"); try (BufferedReader reader = Files.newBufferedReader(file, charset)) {     String line = null;     while ((line = reader.readLine()) != nothing) {         Arrangement.out.println(line);     } } grab (IOException x) {     System.err.format("IOException: %due south%due north", 10); }          

Writing a File by Using Buffered Stream I/O

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

The post-obit code snippet shows how to create a file encoded in "U.s.a.-ASCII" using this method:

Charset charset = Charset.forName("United states-ASCII"); String south = ...; effort (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {     author.write(s, 0, s.length()); } grab (IOException x) {     Organisation.err.format("IOException: %s%n", x); }          

Methods for Unbuffered Streams and Interoperable with coffee.io APIs

Reading a File past Using Stream I/O

To open a file for reading, you can apply the newInputStream(Path, OpenOption...) method. This method returns an unbuffered input stream for reading bytes from the file.

Path file = ...; endeavour (InputStream in = Files.newInputStream(file);     BufferedReader reader =       new BufferedReader(new InputStreamReader(in))) {     Cord line = null;     while ((line = reader.readLine()) != null) {         System.out.println(line);     } } catch (IOException ten) {     System.err.println(x); }          

Creating and Writing a File by Using Stream I/O

You tin 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 up options are specified, and the file does not be, a new file is created. If the file exists, information technology is truncated. This option is equivalent to invoking the method with the CREATE and TRUNCATE_EXISTING options.

The following instance 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 java.nio.file.*; import java.io.*;  public class LogFileTest {    public static void main(String[] args) {      // Convert the cord to a     // byte array.     String southward = "Hello World! ";     byte data[] = s.getBytes();     Path p = Paths.get("./logfile.txt");      attempt (OutputStream out = new BufferedOutputStream(       Files.newOutputStream(p, CREATE, Suspend))) {       out.write(data, 0, data.length);     } grab (IOException x) {       System.err.println(10);     }   } }          

Methods for Channels and ByteBuffers

Reading and Writing Files past Using Channel I/O

While stream I/O reads a grapheme at a fourth dimension, aqueduct 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 motion to unlike points in the file and then read from or write to that location makes random admission of a file possible. Come across Random Access Files for more than information.

At that place are two methods for reading and writing channel I/O.

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

Note: The newByteChannel methods render an example of a SeekableByteChannel. With a default file organisation, you can cast this seekable byte channel to a FileChannel providing access to more avant-garde features such mapping a region of the file straight into memory for faster access, locking a region of the file so other processes cannot access information technology, or reading and writing bytes from an absolute position without affecting the aqueduct's electric current position.


Both newByteChannel methods enable you to specify a list of OpenOption options. The same open options used by the newOutputStream methods are supported, in improver 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 lawmaking 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)) {         last int BUFFER_CAPACITY = 10;         ByteBuffer buf = ByteBuffer.allocate(BUFFER_CAPACITY);          // Read the bytes with the proper encoding for this platform. If         // y'all skip this pace, yous might run across foreign or illegible         // characters.         String encoding = System.getProperty("file.encoding");         while (sbc.read(buf) > 0) {             buf.flip();             Organization.out.print(Charset.forName(encoding).decode(buf));             buf.clear();         }     }     }          

The following instance, written for UNIX and other POSIX file systems, creates a log file with a specific fix of file permissions. This lawmaking creates a log file or appends to the log file if information technology 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 coffee.nio.channels.*; import coffee.nio.file.*; import java.nio.file.attribute.*; import java.io.*; import java.util.*;  public course LogFilePermissionsTest {    public static void principal(Cord[] args) {        // Create the set of options for appending to the file.     Set<OpenOption> options = new HashSet<OpenOption>();     options.add together(APPEND);     options.add(CREATE);      // Create the custom permissions aspect.     Set<PosixFilePermission> perms =       PosixFilePermissions.fromString("rw-r-----");     FileAttribute<Set<PosixFilePermission>> attr =       PosixFilePermissions.asFileAttribute(perms);      // Convert the string to a ByteBuffer.     String south = "Hello World! ";     byte information[] = south.getBytes();     ByteBuffer bb = ByteBuffer.wrap(information);          Path file = Paths.go("./permissions.log");      try (SeekableByteChannel sbc =       Files.newByteChannel(file, options, attr)) {       sbc.write(bb);     } grab (IOException x) {       System.out.println("Exception thrown: " + x);     }   } }          

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 instance, if, at the fourth dimension of cosmos, yous want a file to have a particular set of file permissions, utilise 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 beingness 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:

Path file = ...; attempt {     // Create the empty file with default permissions, etc.     Files.createFile(file); } catch (FileAlreadyExistsException x) {     Arrangement.err.format("file named %s" +         " already exists%n", file); } catch (IOException x) {     // Another sort of failure, such every bit permissions.     Organisation.err.format("createFile error: %s%due north", x); }          

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 shut information technology immediately, an empty file is created.

Creating Temporary Files

Yous can create a temporary file using 1 of the post-obit createTempFile methods:

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

The offset 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 y'all to specify a suffix for the filename and the first method allows you to also specify a prefix. The following lawmaking snippet gives an example of the 2d method:

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

The outcome 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 noun is platform specific.

perezwhisair1941.blogspot.com

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

0 Response to "Program to Read a File From a Given Location in Java and Print"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel