How to print a file in Java?

One way to print the contents of a file in Java is by using classes from the java.io package. Below is an example code demonstrating how to print the contents of a file.

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class FilePrinter {

    public static void main(String[] args) {

        String filePath = "path/to/your/file.txt";  // 文件路径

        

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {

            String line;

            while ((line = reader.readLine()) != null) {

                System.out.println(line);  // 打印每一行内容

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

The code above first specifies the path of the file to print (`filePath` variable), then it uses `BufferedReader` and `FileReader` to read the file content. Inside a loop, it reads the file content line by line and prints it to the console using `System.out.println()` method.

Make sure to replace `path/to/your/file.txt` with the actual file path you want to print. Running this code will display the contents of the file in lines.

bannerAds