Programmers use text files in Java while working with Java applications that require reading and writing on a file. Text files are universal ways to store information, code, or any other data. A text file is considered a sequence of characters organized horizontally. The text files in Java have extensions such as .java containing Java codes. Java provides different utilities allowing you to deal with plain text files by either reading from them or writing to them. You can choose any read/write utility per your understanding.
Key Highlights
- A text file is made of different characters, where one can perform read and write operations using java.io.package.
- To read, you can use Reader Class or utility class. Some utility classes are- File Class, FileReader, BufferedReader, and Scanner class.
- To write to a file in Java, you can use Java 7 Files, FileWriter, BufferedWriter, and FileOutputStream.
- Using different methods, you can efficiently work around text files in Java.
How to Read Text Files in Java?
- In text files, each line has plain characters, and each line is marked by an invisible “end-of-line” symbol representing the end of that specific line.
- For reading text files in Java, different utilities are available. Each utility has its way of reading from the text file and offers some functionality that differs from other alternatives.
- Here we will explain different methods with a good example for better understanding.
Before starting with the methods, we are considering a text file “test.txt” at path “/Users/praashibansal/Desktop/Data/test.txt” with the content ”Hello, there”.
ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock TestsMethod 1 – Using BufferedReader Class
- You can use this method to read text from the character-input stream. You can use the default buffer size (8KB) or specify your own. It supports encoding.
- Each request has a Reader that creates a read request made of the underlying character stream or byte stream.
- Thus many developers recommend wrapping a BufferedReader around any Reader using its read() operations.
- It works well for processing large files. This method is synchronized and thus can be used from multiple threads.
Code:
import java.io.*; public class BReader { public static void main(String[] args) throws Exception { File f = new File( "https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); // Creating an object BufferedReader b = new BufferedReader(new FileReader(f)); // Declaring a string variable String s; // Condition holds till // there is a character in a string while ((s = b.readLine()) != null) // Print the string System.out.println(s); } }
Output:
Method 2 – Using FileReader Class
- You can use FileReader to get the BufferedReader and start reading the file.
- Unlike BufferedReader, it doesn’t support encoding and instead uses the system’s default encoding.
- It is just a simple way of reading characters.
- This class uses three constructors.
- FileReader(File file): Creates a new FileReader. The file is the file from which you will read the content.
- FileReader(FileDescriptor fd): Creates a new FileReader that reads from the file specified as FileDescriptor.
- FileReader(String fileName): Creates a new FileReader that will read from the file named fileName.
Code:
import java.io.*; public class RFile { public static void main(String[] args) throws Exception { // Passing the file’s path FileReader f = new FileReader( "https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); // declaring loop variable int i; while ((i = f.read()) != -1) // Print the content of a file System.out.print((char)i); } }
Output:
Method 3 – Using Scanner Class
- It is a simple text scanner, and it is capable of parsing primitive types and strings via regular expression.
- It breaks the input into tokens via a delimiter pattern. By default, the delimiter is the whitespace.
- Then the token converts into different types of values.
Code:
import java.io.File; import java.util.Scanner; public class ReadScan { public static void main(String[] args) throws Exception { // passing the file’s path File file = new File("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); Scanner s = new Scanner(file); while (s.hasNextLine()) System.out.println(s.nextLine()); } }
Output:
Method 4 – Using the Files Class Method
- Files class USES the following methods for reading the file.
- readAllBytes(Path path): reads all the bytes from the file and returns the byte array containing the bytes from the file.
- readAllLines(Path path, Charsetcs): reads all lines from the file and returns the List with the lines from the file.
Code:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FCExample { public static void main(String[] args) { Path path = Paths.get("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); try { byte[] b = Files.readAllBytes(path); System.out.println("Read bytes: \n"+new String(b)); } catch (IOException e) { } } }
Output:
How to Write a Text File in Java?
- Writing a text file in Java is also a simple process. Java offers different utilities to help write the lines to the file.
- Now for this process, we are assuming a file at the location- C:\\Users\\Data\\Desktop\\write.txt to which we are writing.
Method 1 – Using FileWriter Method
- This all-in-one method allows you to write int, byte array, and String to the File.
- It allows you to write directly into Files and is used in case of the less writes.
- Using the FileWriter method, you can write part of the String or byte array.
Code:
import java.io.FileWriter; public class FWFile { public static void main(String args[]){ try{ FileWriter f=new FileWriter("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); f.write("Hello"); f.close(); } catch(Exception e) { System.out.println(e); } System.out.println("Hello"); } }
Output:
Method 2 – Using BufferedWriter Method
- BufferedWriter is similar to FileWriter, but BufferedWriter uses an internal buffer to write data into File.
- It works well if you need to do more write operations and to ensure performance.
Code:
import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public class BRExample { public static void main(String args[]) { String data = "data for output file"; try { // Creates a FileWriter FileWriter file = new FileWriter("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); try ( // Creates a BufferedWriter var o = new BufferedWriter(file)) { // Writes the string to the file o.write(data); } } catch (IOException e) { e.getStackTrace(); } } }
Output:
Method 3 – Using FileOutputStream Method
- For writing text to the file, you can simply use FileWriter and BufferedWriter.
- But, if you want the raw stream data to be written directly into a file, it is recommended to use the FileOutputStream utility.
- With this method, you must create the class object with the specific filename to write data into a file.
- The following example converts the string content into the byte array we will write into the file using the write() method.
Code:
import java.io.FileOutputStream; import java.io.IOException; public class GFG { public static void main(String[] args) { String f = "Hello"; FileOutputStream o = null; // starting Try block try { // creating an object of FileOutputStream o = new FileOutputStream("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); // storing byte content from string byte[] str = f.getBytes(); // writing into the file o.write(str); // printing success message System.out.print( "data added successfully."); } // Catch block for exception handling catch (IOException e) { System.out.print(e.getMessage()); } finally { // closing the object if (o != null) { // checking if the file is closed try { o.close(); } catch (IOException e) { // showing exception message System.out.print(e.getMessage()); } } } } }
Output:
Method 4 – Using Files Class
- In Java 7, you will get another utility, Files class, allowing you to write to a text file using its write function.
- Internally, this class uses the OutputStream utility to write a byte array into the file.
Code:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Java Files write file example * * @author pankaj * */ public class FCExample { public static void main(String[] args) { Path path = Paths.get("https://cdn.educba.com/Users/praashibansal/Desktop/Data/test.txt"); try { String str = "Example"; byte[] bs = str.getBytes(); Path w = Files.write(path, bs); System.out.println("Written content in file:\n"+ new String(Files.readAllBytes(w))); } catch (IOException e) { } } }
Output:
Conclusion
Reading and writing a file in Java is a straightforward process. With the availability of different methods and utilities in Java, you can choose a specific way to read from and write to a file. Each utility has its functionality that makes it different from others.
FAQs
Q1. What are the different methods to read a text file in Java?
Answer: To read, you can use Reader Class or utility class. Some utility classes are- File Class, FileReader, BufferedReader, and Scanner class.
Q2. What are the different methods for writing a text file in Java?
Answer: To write a file in Java, you can use FileWriter, BufferedWriter, java 7 Files, FileOutputStream, and many other methods.
Q3. What package to use for handling files in Java?
Answer: You can easily import the File class from the java.io package to work with files.
The above is the detailed content of Text File in Java. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment