Java Write To File

Java Write To File Average ratng: 9,8/10 7563 reviews

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.

Writing to a file is a little easier than reading a file. To write to a file, we'll use two more inbuilt classes: the FileWriter class and the PrintWriter class. Create a new class in your project by clicking File New File from the NetBeans menu. Select Java in the Categories section of the dialogue box and Class from the File Types list. Click the Next button at the bottom. Write to File in Java. Used to create and write characters to a file. Import java.io.; //create a new File object File fileObject = new File(filenamePath);.

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 java.io package. To the right of those are the methods for dealing with ByteChannels, SeekableByteChannels, and ByteBuffers, such as the newByteChannel method. Finally, on the far right are the methods that use 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 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 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 data to the end of the file. This option is used with the WRITE or CREATE options.
  • TRUNCATE_EXISTING – Truncates the file to zero bytes. This option 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 not.
  • 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 advanced option is honored on some file systems, such as NTFS, where large files with data 'gaps' can be stored in a more efficient manner where those empty gaps do not consume disk space.
  • 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.

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

Java Write To File

Writing a File by Using Buffered Stream I/O

You 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:

Methods for Unbuffered Streams and Interoperable with java.io APIs

Java Write To File Append

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.

Note: The newByteChannel methods return an instance of a SeekableByteChannel. With a default file system, you can cast this seekable byte channel to a FileChannel providing access to more advanced features such mapping a region of the file directly into memory for faster access, locking a region of the file so other processes cannot access it, or reading and writing bytes from an absolute position without affecting the channel's 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 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 is specified, 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:

Descargar pou para pc. Raise your little alien pet on your PC and continue on your phone! Pou is a new and addictive virtual pet video game for Android devices. First, you have to download the free Bluestacks Android Emulator app for your computer or laptop.

The result of running this file would be something like the following:

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

There are multiple ways of writing and reading a text file. this is required while dealing with many applications.

There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.

We can also use both BufferReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file

Note : Here usual practices of writing good code like flushing/closing streams, Exception-Handling etc, have been avoided for better understanding of codes by beginners as well

Here are some of the many ways of reading files:

  1. Using BufferedReader: This method reads text from a character-input stream. It does buffering for efficient reading of characters, arrays, and lines.
    The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

    In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,


    // Java Program to illustrate reading from FileReader
    importjava.io.*;
    {
    publicstaticvoidmain(String[] args)throwsException
    // We need to provide file path as the parameter:
    // double backquote is to avoid compiler interpret words
    File file = newFile('C:UserspankajDesktoptest.txt');
    BufferedReader br = newBufferedReader(newFileReader(file));
    String st;
    System.out.println(st);
    }
  2. Using FileReader class: Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.
    Constructors defined in this class are:
    // FileReader using FileReader
    publicclassReadingFromFile
    publicstaticvoidmain(String[] args) throwsException
    // pass the path to the file as a parameter
    newFileReader('C:UserspankajDesktoptest.txt');
    inti;
    System.out.print((char) i);
    }
  3. Using Scanner class: A simple text scanner which can parse primitive types and strings using regular expressions.
    A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
    // Java Program to illustrate reading from Text File
    importjava.io.File;
    publicclassReadFromFileUsingScanner
    publicstaticvoidmain(String[] args) throwsException
    // pass the path to the file as a parameter
    newFile('C:UserspankajDesktoptest.txt');
    System.out.println(sc.nextLine());
    }
  4. Using Scanner class but without using loops:
    // Java Program to illustrate reading from FileReader
    // without using loop
    importjava.io.FileNotFoundException;
    {
    throwsFileNotFoundException
    File file = newFile('C:UserspankajDesktoptest.txt');
    sc.useDelimiter('Z');
    System.out.println(sc.next());
    }
  5. Reading the whole file in a List: Read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.

    This method recognizes the following as line terminators:

    // Java program to illustrate reading data from file
    importjava.util.*;
    importjava.nio.file.*;
    publicclassReadFileIntoList
    publicstaticList<String> readFileInList(String fileName)
    try
    lines =
    Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
    {
    // do something
    }
    }
    {
    List l = readFileInList('C:UserspankajDesktoptest.java');
    Iterator<String> itr = l.iterator();
    System.out.println(itr.next());
    }
  6. Read a text file as String in Java:
    // Java Program to illustrate reading from text file
    packageio;
    publicclassReadTextAsString
    publicstaticString readFileAsString(String fileName)throwsException
    String data = ';
    data = newString(Files.readAllBytes(Paths.get(fileName)));
    }
    publicstaticvoidmain(String[] args) throwsException
    String data = readFileAsString('C:UserspankajDesktoptest.java');
    }

References:

https://docs.oracle.com/javase/7/docs/api/java/io/package-summary.html
http://docs.oracle.com/javase/tutorial/essential/io/

This article is contributed byPankaj Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Recommended Posts: