📜  如何使用Java从文本文档中提取内容?

📅  最后修改于: 2021-10-28 02:14:06             🧑  作者: Mango

Java有几种方法可以读取文本文件,如BufferReader、FileReader和Scanner。每一种方法都提供了一种独特的文本文件读取方式。

方法:

  1. 使用 Files 类
  2. 使用 FileReader 类
  3. 使用 BufferReader 类
  4. 使用 Scanner 类

让我们通过示例详细了解每种方法,以便更好地理解这些方法,以便稍后实现从文本文档中提取内容的方法。

方法一:使用 Files 类

正如Java提供的 Java.nio.file 应用程序接口 我们可以使用Java.nio.file.Files 类将文件的所有内容读入数组。要读取文本文件,我们可以使用 Files 类的readAllBytes() 方法,当您需要内存中的所有文件内容以及处理小文件时,可以使用该方法。

例子:

Java
// Java Program to Extract Content From a Text Document
// Using Files class
 
// Importing java.nio package for network linking
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
// Importing List class from java.util package
import java.util.List;
 
// Main class
public class GFG {
    // Method 1
    // To read the file using class
    private static void readUsingClass(String fileName)
        throws IOException
    {
        // Creating an object of Path class
        Path path = Paths.get(fileName);
 
        // To read file to byte array
        byte[] bytes = Files.readAllBytes(path);
 
        // Display message only
        System.out.println(
            "Read text file using Files class");
 
        // Reading the file to String List
        @SuppressWarnings("unused")
 
        // Creating a List class object of string type
        // as data in file to be read is words
        List allLines = Files.readAllLines(
            path, StandardCharsets.UTF_8);
        System.out.println(new String(bytes));
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        // Custom input directory passed where text
        String fileName
            = "/Users/mayanksolanki/Desktop/file.txt";
 
        // read using FileReader, no encoding support, not
        // efficient
        readUsingClass(fileName);
    }
}


Java
// Java Program to Extract Content From a Text Document
// Using FileReader class
 
// Importing required libraries
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
 
// Main class
public class GFG {
    // Method
    // To read the file using File Reader
    private static void readUsingFileReader(String fileName)
        throws IOException
    {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println(
            "Reading text file using FileReader");
        while ((line = br.readLine()) != null) {
            // process the line
            System.out.println(line);
        }
        br.close();
        fr.close();
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        String fileName
            = "/Users/mayanksolanki/Desktop/file.txt";
 
        // read using FileReader, no encoding support, not
        // efficient
        readUsingFileReader(fileName);
    }
}


Java
// Java Program to Extract Content From a Text Document
// Using BufferedReader class
 
// Importing required libraries
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
 
// Main class
public class GFG {
    // Method
    // To read the file using Buffered Reader
    private static void
    readUsingBufferedReader(String fileName)
        throws IOException
    {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        // read file line by line
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println(
            "Read text file using BufferedReader");
        while ((line = br.readLine()) != null) {
            // process the line
            System.out.println(line);
        }
        // close resources
        br.close();
        fr.close();
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        String fileName
            = "/Users/mayanksolanki/Desktop/file.txt";
 
        // read using FileReader, no encoding support, not
        // efficient
        readUsingBufferedReader(fileName);
    }
}


Java
// Java Program to Extract Content From a Text Document
// Using Scanner class
 
// Importing required libraries
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
 
// Main class
public class GFG {
   
    // Method 1
    // To read the file using Scanner
    private static void readUsingScanner(String fileName)
        throws IOException
    {
 
        // Again,  creating Path class object in main()
        // method
        Path path = Paths.get(fileName);
 
        // Creating Scanner class object to take input
        Scanner scanner = new Scanner(path);
 
        // Display message for readability
        System.out.println("Read text file using Scanner");
 
        // Now reading file line by line
        // using hasNextLine() method
        while (scanner.hasNextLine()) {
 
            // Processing each line
            String line = scanner.nextLine();
 
            // Printing processed lines
            System.out.println(line);
        }
 
        // close() method is used to close all the read
        // write connections
        scanner.close();
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        // Custom input text document
        // present already on the machine
        String fileName
            = "/Users/mayanksolanki/Desktop/file.txt";
 
        // Now lastly reading using FileReader
        // no encoding support, not efficient
        readUsingScanner(fileName);
    }
}


Java
// Java Program to Implement Extraction of Content
// From a Text Document
 
// Importing required libraries
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
 
// Main class
public class read_file {
    // Method 1
    // To read the file using File Reader
    private static void readUsingFileReader(String fileName)
        throws IOException
    {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println(
            "Reading text file using FileReader");
        while ((line = br.readLine()) != null) {
            // process the line
            System.out.println(line);
        }
        br.close();
        fr.close();
    }
 
    // Method 2
    // To read the file using Buffered Reader
    private static void
    readUsingBufferedReader(String fileName)
        throws IOException
    {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        // read file line by line
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println(
            "Read text file using BufferedReader");
        while ((line = br.readLine()) != null) {
            // process the line
            System.out.println(line);
        }
 
        // Closing resources to
        // release memory spaces
        br.close();
        fr.close();
    }
 
    // Method 3
    // To read the file using Scanner
    private static void readUsingScanner(String fileName)
        throws IOException
    {
        Path path = Paths.get(fileName);
        Scanner scanner = new Scanner(path);
        System.out.println("Read text file using Scanner");
        // read line by line
        while (scanner.hasNextLine()) {
            // process each line
            String line = scanner.nextLine();
            System.out.println(line);
        }
        scanner.close();
    }
 
    // Method 4
    // To read the file using class
    private static void readUsingClass(String fileName)
        throws IOException
    {
        Path path = Paths.get(fileName);
        // read file to byte array
        byte[] bytes = Files.readAllBytes(path);
        System.out.println(
            "Read text file using Files class");
        // read file to String list
        @SuppressWarnings("unused")
        List allLines = Files.readAllLines(
            path, StandardCharsets.UTF_8);
        System.out.println(new String(bytes));
    }
 
    // Method 5
    // main driver method
    public static void main(String[] args)
        throws IOException
    {
        String fileName
            = "C:\\Users\\HP\\Desktop\\my_file.txt";
 
        // using Java 7 Files class to
        // process small files, get complete file data
        readUsingClass(fileName);
 
        // using Scanner class for
        // large files, to read line by line
        readUsingScanner(fileName);
 
        // read using BufferedReader, to read line by line
        readUsingBufferedReader(fileName);
 
        // read using FileReader, no encoding support, not
        // efficient
        readUsingFileReader(fileName);
    }
}


Java
// Java program to Read Specific Lines from a Text File
 
// Importing required libraries
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Initially taking empty string
        String text = "";
 
        // Declaring a variable to lookup for
        // number of lines in afile
        int lineNumber;
 
        // Try block to check for exceptions
        try {
           
            // Creating a FileReader object so as to
            // get the directory of file to be read
            FileReader readfile = new FileReader(
                "C:\\Users\\HP\\Desktop\\Exam.txt");
 
            // Creating a BufferReader class object to
            // read file as passed above
            BufferedReader readbuffer
                = new BufferedReader(readfile);
 
            // Buffer reader declaration
 
            // Conditionality for specific line/s
 
            // Loop for the traversing line by line
            // into the text file
            for (lineNumber = 1; lineNumber < 10;
                 lineNumber++) {
                // If spefic line/s is found
                if (lineNumber == 7) {
                    // Store the content of this specific
                    // line
                    text = readbuffer.readLine();
                }
 
                else {
                    // Just keep on reading
                    readbuffer.readLine();
                }
            }
        }
 
        // Catching IOException exception
        catch (IOException e) {
 
            // Print the line number where exception occurred
            e.printStackTrace();
        }
 
        // Print the specific line from the file read
        System.out.println(" The specific Line is: "
                           + text);
    }
}


输出:

方法二:使用 FileReader 类 

我们可以使用Java.io.FileReader从文件中读取数据(以字符)。这是一种非常有效的逐行读取文件的方法。

句法:

FileReader input = new FileReader(String name);

例子:

Java

// Java Program to Extract Content From a Text Document
// Using FileReader class
 
// Importing required libraries
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
 
// Main class
public class GFG {
    // Method
    // To read the file using File Reader
    private static void readUsingFileReader(String fileName)
        throws IOException
    {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println(
            "Reading text file using FileReader");
        while ((line = br.readLine()) != null) {
            // process the line
            System.out.println(line);
        }
        br.close();
        fr.close();
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        String fileName
            = "/Users/mayanksolanki/Desktop/file.txt";
 
        // read using FileReader, no encoding support, not
        // efficient
        readUsingFileReader(fileName);
    }
}

输出:

方法 3:使用 BufferedReader 类 

如果你想阅读 逐行文件,如果要处理该文件,则必须使用 BufferedReader。它也用于处理大文件,它也支持编码。 BufferReader 上的读取操作非常高效。

句法:

BufferedReader in = new BufferedReader(Reader in, int size);

执行:

Hello I am learning web- development.
I am writing article for GFG.
I am cloud enthusiast.
I am an open-source contributor.

例子:

Java

// Java Program to Extract Content From a Text Document
// Using BufferedReader class
 
// Importing required libraries
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
 
// Main class
public class GFG {
    // Method
    // To read the file using Buffered Reader
    private static void
    readUsingBufferedReader(String fileName)
        throws IOException
    {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        // read file line by line
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println(
            "Read text file using BufferedReader");
        while ((line = br.readLine()) != null) {
            // process the line
            System.out.println(line);
        }
        // close resources
        br.close();
        fr.close();
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        String fileName
            = "/Users/mayanksolanki/Desktop/file.txt";
 
        // read using FileReader, no encoding support, not
        // efficient
        readUsingBufferedReader(fileName);
    }
}

输出:

方法 4:使用 Scanner 类

如果我们想根据一些表达式读取文档&如果要逐行读取文档,那么我们使用 Scanner 类。 Scanner 将输入分解为标记,默认情况下与空白匹配。

例子 :

Java

// Java Program to Extract Content From a Text Document
// Using Scanner class
 
// Importing required libraries
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
 
// Main class
public class GFG {
   
    // Method 1
    // To read the file using Scanner
    private static void readUsingScanner(String fileName)
        throws IOException
    {
 
        // Again,  creating Path class object in main()
        // method
        Path path = Paths.get(fileName);
 
        // Creating Scanner class object to take input
        Scanner scanner = new Scanner(path);
 
        // Display message for readability
        System.out.println("Read text file using Scanner");
 
        // Now reading file line by line
        // using hasNextLine() method
        while (scanner.hasNextLine()) {
 
            // Processing each line
            String line = scanner.nextLine();
 
            // Printing processed lines
            System.out.println(line);
        }
 
        // close() method is used to close all the read
        // write connections
        scanner.close();
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
        // Custom input text document
        // present already on the machine
        String fileName
            = "/Users/mayanksolanki/Desktop/file.txt";
 
        // Now lastly reading using FileReader
        // no encoding support, not efficient
        readUsingScanner(fileName);
    }
}

输出:

执行:

这里“ my_file.txt”是用于下面演示的程序的演示文件,其中示例行如下:

Hello I am learning web- development.
I am writing article of GFG.
I am cloud enthusiast.
I am an open-source contributor.

示例 1:

Java

// Java Program to Implement Extraction of Content
// From a Text Document
 
// Importing required libraries
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
 
// Main class
public class read_file {
    // Method 1
    // To read the file using File Reader
    private static void readUsingFileReader(String fileName)
        throws IOException
    {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println(
            "Reading text file using FileReader");
        while ((line = br.readLine()) != null) {
            // process the line
            System.out.println(line);
        }
        br.close();
        fr.close();
    }
 
    // Method 2
    // To read the file using Buffered Reader
    private static void
    readUsingBufferedReader(String fileName)
        throws IOException
    {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        // read file line by line
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println(
            "Read text file using BufferedReader");
        while ((line = br.readLine()) != null) {
            // process the line
            System.out.println(line);
        }
 
        // Closing resources to
        // release memory spaces
        br.close();
        fr.close();
    }
 
    // Method 3
    // To read the file using Scanner
    private static void readUsingScanner(String fileName)
        throws IOException
    {
        Path path = Paths.get(fileName);
        Scanner scanner = new Scanner(path);
        System.out.println("Read text file using Scanner");
        // read line by line
        while (scanner.hasNextLine()) {
            // process each line
            String line = scanner.nextLine();
            System.out.println(line);
        }
        scanner.close();
    }
 
    // Method 4
    // To read the file using class
    private static void readUsingClass(String fileName)
        throws IOException
    {
        Path path = Paths.get(fileName);
        // read file to byte array
        byte[] bytes = Files.readAllBytes(path);
        System.out.println(
            "Read text file using Files class");
        // read file to String list
        @SuppressWarnings("unused")
        List allLines = Files.readAllLines(
            path, StandardCharsets.UTF_8);
        System.out.println(new String(bytes));
    }
 
    // Method 5
    // main driver method
    public static void main(String[] args)
        throws IOException
    {
        String fileName
            = "C:\\Users\\HP\\Desktop\\my_file.txt";
 
        // using Java 7 Files class to
        // process small files, get complete file data
        readUsingClass(fileName);
 
        // using Scanner class for
        // large files, to read line by line
        readUsingScanner(fileName);
 
        // read using BufferedReader, to read line by line
        readUsingBufferedReader(fileName);
 
        // read using FileReader, no encoding support, not
        // efficient
        readUsingFileReader(fileName);
    }
}

示例 2:从文本文件中读取特定行

现在如果你想从给定的文档中读取特定的行,那么我们使用 BufferReader 方法。根据文件 BufferReader() 方法的使用,我们的代码运行得更快更高效。在这个程序中,BufferReader中存储的Text文件是使用for循环遍历所有行,当条件成立时,我们将打印该行

执行:

这是包含在此文件中的样本行,由行组成的随机任意词组成

Java

// Java program to Read Specific Lines from a Text File
 
// Importing required libraries
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Initially taking empty string
        String text = "";
 
        // Declaring a variable to lookup for
        // number of lines in afile
        int lineNumber;
 
        // Try block to check for exceptions
        try {
           
            // Creating a FileReader object so as to
            // get the directory of file to be read
            FileReader readfile = new FileReader(
                "C:\\Users\\HP\\Desktop\\Exam.txt");
 
            // Creating a BufferReader class object to
            // read file as passed above
            BufferedReader readbuffer
                = new BufferedReader(readfile);
 
            // Buffer reader declaration
 
            // Conditionality for specific line/s
 
            // Loop for the traversing line by line
            // into the text file
            for (lineNumber = 1; lineNumber < 10;
                 lineNumber++) {
                // If spefic line/s is found
                if (lineNumber == 7) {
                    // Store the content of this specific
                    // line
                    text = readbuffer.readLine();
                }
 
                else {
                    // Just keep on reading
                    readbuffer.readLine();
                }
            }
        }
 
        // Catching IOException exception
        catch (IOException e) {
 
            // Print the line number where exception occurred
            e.printStackTrace();
        }
 
        // Print the specific line from the file read
        System.out.println(" The specific Line is: "
                           + text);
    }
}

输出:具体行是:

3D printing enables you to produce complex shapes.