SoFunction
Updated on 2025-04-05

Detailed explanation of reading and writing TXT text in daily Java development

Preface

In an era of surging digital waves, program development is like a mysterious and magnificent magic castle, standing in the vast starry sky of technology. The characters in the code are like the twinkling stars, combined, intertwined and collided according to specific trajectories and rhythms, and are about to embark on a wonderful and creative journey full of infinite possibilities. When the blank document interface is like a deep universe waiting to be explored, programmers transform into fearless star pioneers, dancing lightly on the keyboard with their fingertips, preparing to use wisdom and logic to weave a program scroll that is enough to change the rules of the world's operation, and in the binary world of 0 and 1, they engrave the immortal mark of human innovation and breakthrough.

1. Read TXT text

1.1 Read with BufferedReader

  • Principle: BufferedReader is a class in Java for efficient reading of character streams. It can read text from a character input stream (such as FileReader) and provide buffering functions to reduce frequent access to underlying resources and improve reading efficiency.

Step Example:

1. First, you need to import the relevant packages and.

import ;
import ;
import ;

2. Then, use the try-catch block to handle possible IOExceptions. In the try block, create a FileReader object to associate the text file to be read, and pass it to the BufferedReader object.

public class ReadTxtFile {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(""));
            String line;
            while ((line = ())!= null) {
                (line);
            }
            ();
        } catch (IOException e) {
            ();
        }
    }
}

In the above code, the () method is used to read the text content line by line, and returns null when it is read to the end of the file. This way, the file content can be printed out line by line through loop. Finally, remember to close the BufferedReader and release the resources.

1.2 Read with Scanner

Principle: The Scanner class provides an easy way to parse various basic data types and strings. When used to read a text file, it can parse text content based on the specified delimiter (default is a space).

Step Example:

Import and package.

import ;
import ;
import ;

Also operate in the try - catch block. Create a Scanner object and pass it as a parameter to the text file opened through the File object.

public class ReadTxtFileWithScanner {
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(new File(""));
            while (()) {
                (());
            }
            ();
        } catch (FileNotFoundException e) {
            ();
        }
    }
}

Here () is used to determine whether there is still the next line of content, and () is used to read the next line of content and return. Finally close the Scanner object.

Byte stream read (FileInputStream) and converted to character stream (suitable for situations where reading non-text encoding may be problematic)

Principle: FileInputStream is used to read file contents in a byte stream. If you want to convert a byte stream to a character stream to process text content, you can wrap it in an InputStreamReader and then use a BufferedReader for buffering reading, which can handle some specially encoded text files.

Step Example:

Import, and package.

import ;
import ;
import ;
import ;

In the try - catch block, first create the FileInputStream object, then pass it to the InputStreamReader, and then pass it to the BufferedReader for reading.

public class ReadTxtFileWithByteStream {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("");
            InputStreamReader isr = new InputStreamReader(fis, "UTF - 8");
            BufferedReader reader = new BufferedReader(isr);
            String line;
            while ((line = ())!= null) {
                (line);
            }
            ();
        } catch (IOException e) {
            ();
        }
    }
}

In the above code, the second parameter in the InputStreamReader constructor specifies the encoding method of the file (here is UTF - 8), which can be modified according to the actual situation.

2. Write TXT text

2.1 Write using BufferedWriter

Principle: BufferedWriter is a class used to write text to character output streams. It provides buffering function, reduces the number of physical write operations and improves write efficiency.

Step Example:Import and package.

import ;
import ;
import ;

In the try - catch block, create a FileWriter object to associate the text file to be written, and pass it to the BufferedWriter object. Use the write method to write the content, and finally write the buffer content to the file through the flush method, and close the BufferedWriter.

public class WriteTxtFile {
    public static void main(String[] args) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(""));
            ("This is what you want to write to the text file");
            ();
            ();
        } catch (IOException e) {
            ();
        }
    }
}

2.2 Write using PrintWriter

Principle: PrintWriter provides convenient printing methods to write various data types (such as integers, floating point numbers, strings, etc.) to the text output stream. It can automatically convert data into strings and write to files.

Step Example:

Import and package.

import ;
import ;
import ;

In the try - catch block, create a PrintWriter object, passing the text file opened through the File object as a parameter. Use println or print method to write content and finally close PrintWriter.

public class WriteTxtFileWithPrintWriter {
    public static void main(String[] args) {
        try {
            PrintWriter writer = new PrintWriter(new File(""));
            ("This is the first line of content");
            ("This is the second line");
            ();
        } catch (FileNotFoundException e) {
            ();
        }
    }
}

2.3 Convert to character stream after byte stream writing (FileOutputStream) (suitable for special encoding writing, etc.)

Principle: FileOutputStream is used to write data to a file in a byte stream. If you want to convert a byte stream into a character stream to write text content, you can wrap it in an OutputStreamReader and then use a BufferedWriter for buffered writing. This method is more useful when handling writing of special encoded files.

Step Example:

Import, and package.

import ;
import ;
import ;
import ;

In the try - catch block, first create the FileOutputStream object, then pass it to the OutputStreamReader, and then pass it to the BufferedWriter for writing.

public class WriteTxtFileWithByteStream {
    public static void main(String[] args) {
        try {
            FileOutputStream fos = new FileOutputStream("");
            OutputStreamReader osw = new OutputStreamReader(fos, "UTF - 8");
            BufferedWriter writer = new BufferedWriter(osw);
            ("This is what to write");
            ();
            ();
        } catch (IOException e) {
            ();
        }
    }
}

Similarly, the second parameter in the OutputStreamReader constructor specifies how the file is encoded.

3. Things to note

3.1 File path issues

File paths are a key factor when reading and writing files. The relative path is relative to the current working directory. In Java, the current working directory can be obtained by (""). If the file is located in a specific directory of the project, ensure the correctness of the path.

For example, if the file is located in the resource directory of the project, in an IDE such as Eclipse, the relative path may need to be adjusted according to the structure of the project, which may be src/main/resources/, etc.

3.2 Coding issues

There are many encoding methods for text files, such as UTF - 8, GBK, etc. When reading and writing, ensure consistency in encoding methods. If the encoding method is inconsistent, it may lead to garbled code problems.
For example, when reading a file that uses UTF-8 encoding, you should use InputStreamReader or BufferedReader and specify UTF-8 encoding to read the content correctly. Similarly, when writing files, you should also choose the appropriate encoding method according to your needs.

3.3 Resource release issues

Whether reading or writing files, open streams (such as BufferedReader, BufferedWriter, etc.) must be closed in time to free up system resources. If the stream is not closed, resource leakage may occur, especially in cases where files are frequently read or written.

You can use the try - with - resources statement to automatically close resources, which is supported starting in Java 7. For example, when reading a file:

try (BufferedReader reader = new BufferedReader(new FileReader(""))) {
    String line;
    while ((line = ())!= null) {
        (line);
    }
} catch (IOException e) {
    ();
}

In the try - with - resources statement, when the code block is executed, the resource's close method will be automatically called, which can manage resources more conveniently and safely.

Conclusion

Dear friend, no matter how long and rugged the road ahead is, please keep the spark of your dreams, because in the vast starry sky of life, there is always a brilliant star that belongs to you shining brightly, waiting for you to arrive.

May you always reap small and certain happiness in this complex world, like the spring breeze blowing on your face, all your fatigue and worries can be treated gently, and your heart will always be filled with peace and comfort.

This is the end of this article about the detailed explanation of reading and writing TXT text in Java daily development. For more related content of reading and writing TXT texts in JAVA, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!