Java中读取文本文件的不同方法
有多种写入和读取文本文件的方法。在处理许多应用程序时,这是必需的。有几种方法可以在Java中读取纯文本文件,例如您可以使用 FileReader、BufferedReader 或 Scanner 来读取文本文件。每个实用程序都提供了一些特殊的功能,例如 BufferedReader 提供数据缓冲以便快速读取,而 Scanner 提供解析能力。
方法:
- 使用 BufferedReader 类
- 使用扫描仪类
- 使用文件阅读器类
- 读取列表中的整个文件
- 以字符串形式读取文本文件
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.
Tip Note: Practices of writing good code like flushing/closing streams, Exception-Handling etc, have been avoided for better understanding of codes by beginners as well.
让我们更深入地讨论上述每种方法,最重要的是通过一个干净的Java程序来实现它们。
方法一:使用 BufferedReader 类
此方法从字符输入流中读取文本。它确实缓冲以有效读取字符、数组和行。可以指定缓冲区大小,也可以使用默认大小。对于大多数用途,默认值足够大。通常,由 Reader 发出的每个读取请求都会导致对底层字符或字节流发出相应的读取请求。因此,建议将 BufferedReader 包装在 read() 操作可能成本高昂的任何 Reader 周围,例如 FileReaders 和 InputStreamReaders,如下所示:
BufferedReader in = new BufferedReader(Reader in, int size);
例子:
Java
// Java Program to illustrate Reading from FileReader
// using BufferedReader Class
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// main driver method
public static void main(String[] args) throws Exception
{
// File path is passed as parameter
File file = new File(
"C:\\Users\\pankaj\\Desktop\\test.txt");
// Note: Double backquote is to avoid compiler
// interpret words
// like \test as \t (ie. as a escape sequence)
// Creating an object of BufferedReader class
BufferedReader br
= new BufferedReader(new FileReader(file));
// Declaring a string variable
String st;
// Condition holds true till
// there is character in a string
while ((st = br.readLine()) != null)
// Print the string
System.out.println(st);
}
}
Java
// Java Program to Illustrate reading from
// FileReader using FileReader class
// Importing input output classes
import java.io.*;
// Main class
// ReadingFromFile
public class GFG {
// Main driver method
public static void main(String[] args) throws Exception
{
// Passing the path to the file as a parameter
FileReader fr = new FileReader(
"C:\\Users\\pankaj\\Desktop\\test.txt");
// Declaring loop variable
int i;
// Holds true till there is nothing to read
while ((i = fr.read()) != -1)
// Print all the content of a file
System.out.print((char)i);
}
}
Java
// Java Program to illustrate
// reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
public static void main(String[] args) throws Exception
{
// pass the path to the file as a parameter
File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
Java
// Java Program to illustrate reading from FileReader
// using Scanner Class reading entire File
// without using loop
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop
{
public static void main(String[] args)
throws FileNotFoundException
{
File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
Scanner sc = new Scanner(file);
// we just need to use \\Z as delimiter
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
Java
// Java program to illustrate reading data from file
// using nio.File
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.*;
public class ReadFileIntoList
{
public static List readFileInList(String fileName)
{
List lines = Collections.emptyList();
try
{
lines =
Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
}
catch (IOException e)
{
// do something
e.printStackTrace();
}
return lines;
}
public static void main(String[] args)
{
List l = readFileInList("C:\\Users\\pankaj\\Desktop\\test.java");
Iterator itr = l.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
Java
// Java Program to illustrate
// reading from text file
// as string in Java
package io;
import java.nio.file.*;;
public class ReadTextAsString {
public static String readFileAsString(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main(String[] args) throws Exception
{
String data = readFileAsString("C:\\Users\\pankaj\\Desktop\\test.java");
System.out.println(data);
}
}
输出:
If you want to code refer to GeeksforGeeks
方法二:使用 FileReader 类
读取字符文件的便利类。此类的构造函数假定默认字符编码和默认字节缓冲区大小是适当的。
该类中定义的构造函数如下:
- FileReader(File file):给定要读取的文件,创建一个新的 FileReader
- FileReader(FileDescriptor fd):给定要读取的 FileDescriptor,创建一个新的 FileReader
- FileReader(String fileName):给定要读取的文件名,创建一个新的 FileReader
例子:
Java
// Java Program to Illustrate reading from
// FileReader using FileReader class
// Importing input output classes
import java.io.*;
// Main class
// ReadingFromFile
public class GFG {
// Main driver method
public static void main(String[] args) throws Exception
{
// Passing the path to the file as a parameter
FileReader fr = new FileReader(
"C:\\Users\\pankaj\\Desktop\\test.txt");
// Declaring loop variable
int i;
// Holds true till there is nothing to read
while ((i = fr.read()) != -1)
// Print all the content of a file
System.out.print((char)i);
}
}
输出:
If you want to code refer to GeeksforGeeks
方法 3:使用 Scanner 类
一个简单的文本扫描器,可以使用正则表达式解析原始类型和字符串。 Scanner 使用分隔符模式将其输入分解为标记,默认情况下匹配空格。然后可以使用各种 next 方法将生成的标记转换为不同类型的值。
示例 1:使用循环
Java
// Java Program to illustrate
// reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
public static void main(String[] args) throws Exception
{
// pass the path to the file as a parameter
File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
输出:
If you want to code refer to GeeksforGeeks
示例 2:不使用循环
Java
// Java Program to illustrate reading from FileReader
// using Scanner Class reading entire File
// without using loop
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop
{
public static void main(String[] args)
throws FileNotFoundException
{
File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
Scanner sc = new Scanner(file);
// we just need to use \\Z as delimiter
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
输出:
If you want to code refer to GeeksforGeeks
方法4:读取列表中的整个文件
从文件中读取所有行。此方法确保在读取所有字节或引发 I/O 错误或其他运行时异常时关闭文件。使用指定的字符集将文件中的字节解码为字符。
句法:
public static List readAllLines(Path path,Charset cs)throws IOException
此方法将以下内容识别为行终止符:
\u000D followed by \u000A, CARRIAGE RETURN followed by LINE FEED
\u000A, LINE FEED
\u000D, CARRIAGE RETURN
例子
Java
// Java program to illustrate reading data from file
// using nio.File
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.*;
public class ReadFileIntoList
{
public static List readFileInList(String fileName)
{
List lines = Collections.emptyList();
try
{
lines =
Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
}
catch (IOException e)
{
// do something
e.printStackTrace();
}
return lines;
}
public static void main(String[] args)
{
List l = readFileInList("C:\\Users\\pankaj\\Desktop\\test.java");
Iterator itr = l.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
输出:
If you want to code refer to GeeksforGeeks
方法 5:将文本文件读取为字符串
例子
Java
// Java Program to illustrate
// reading from text file
// as string in Java
package io;
import java.nio.file.*;;
public class ReadTextAsString {
public static String readFileAsString(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main(String[] args) throws Exception
{
String data = readFileAsString("C:\\Users\\pankaj\\Desktop\\test.java");
System.out.println(data);
}
}
输出:
If you want to code refer to GeeksforGeeks