将文件读取为字符串的Java程序
有多种写入和读取文本文件的方法。这在处理许多应用程序时是必需的。在Java有多种方法可以读取纯文本文件,例如您可以使用 FileReader、BufferedReader 或 Scanner 来读取文本文件。
给定一个文本文件,任务是读取本地目录中存在的文件内容并将其存储在字符串。考虑系统上存在的文件,即说它是“gfg.txt”。让文件中的随机内容如下插入 pretag 块中。现在我们将讨论实现相同目标的各种方法。文件“gfg.txt”中的内容如插图块所示。
插图:文件内的行
Geeks-for-Geeks
A computer science portal
World's largest technical hub
Note: Save above text file to your local computer with .txt extension and use that path in the programs.
方法:
实现目标的方式有多种,随着Java版本的推进,也有具体的方法,依次讨论。
方法:
- 使用 File.readString() 方法
- 使用 BufferReader 类的 readLine() 方法
- 使用 File.readAllBytes() 方法
- 使用 File.lines() 方法
- 使用 Scanner 类
让我们通过实现干净的Java程序来讨论它们中的每一个,以便理解它们。
方法一:使用 File.readString() 方法
Java中File类的readString()方法用于读取指定文件的内容。
句法:
Files.readString(filePath) ;
参数:数据类型为Path的文件路径
返回值:此方法以字符串格式返回文件的内容。
Note: File.readString() method was introduced in Java 11 and this method is used to read a file’s content into String.
例子
Java
// Java Program Illustrating Reading a File to a String
// Using Using File.readString() method
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
throws IOException
{
// Creating a path choosing file from local
// directory by creating an object of Path class
Path fileName
= Path.of("C:\\Users\\HP\\Desktop\\gfg.txt");
// Now calling Files.readString() method to
// read the file
String str = Files.readString(fileName);
// Printing the string
System.out.println(str);
}
}
Java
// Java Program Illustrating Reading a File to a String
// Using readLine() method of BufferReader class
// Importing required classes
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
// MAin class
public class GFG {
// Method 1
// To read file content into the string
// using BufferedReader and FileReader
private static String method(String filePath)
{
// Declaring object of StringBuilder class
StringBuilder builder = new StringBuilder();
// try block to check for exceptions where
// object of BufferedReader class us created
// to read filepath
try (BufferedReader buffer = new BufferedReader(
new FileReader(filePath))) {
String str;
// Condition check via buffer.readLine() method
// holding true upto that the while loop runs
while ((str = buffer.readLine()) != null) {
builder.append(str).append("\n");
}
}
// Catch block to handle the exceptions
catch (IOException e) {
// Print the line number here exception occured
// using printStackTrace() method
e.printStackTrace();
}
// Returing a string
return builder.toString();
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Custom input file path stored in string type
String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt";
// Calling the Method 1 to
// read file to a string
System.out.println(method(filePath));
}
}
Java
// Java Program Illustrating Reading a File to a String
// Using File.readAllBytes() method
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
// Main class
public class GFG {
// Method 1
// To read the file content into string with
// Files.readAllBytes(Path path)
private static String method(String file_path)
{
// Declaring an empty string
String str = "";
// Try block to check for exceptions
try {
// Reading all bytes form file and
// storing that in the string
str = new String(
Files.readAllBytes(Paths.get(file_path)));
}
// Catch block to handle the exceptions
catch (IOException e) {
// Print the exception along with line number
// using printStackTrace() method
e.printStackTrace();
}
return str;
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Path is passed from local directory of machine
// and stored in a string
String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt";
// Now call Method1 to
// read the content in above directory
System.out.println(method(filePath));
}
}
Java
// Java Program Illustrating Reading a File to a String
// Using File.lines() method
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
// Main class
public class GFG {
// Method 1
// To read the file content into the string with -
// Files.lines()
private static String method(String filePath)
{
// Declaring an object of StringBuilder class
StringBuilder contentBuilder = new StringBuilder();
// try block to check for exceptions
// Reading file to string using File.lines() method
// and storing it in an object of Stream class
try (Stream stream
= Files.lines(Paths.get(filePath),
StandardCharsets.UTF_8)) {
stream.forEach(
s -> contentBuilder.append(s).append("\n"));
}
// Catch block to handle the exceptions
catch (IOException e) {
// Print the line number where exception occured
// using printStackTrace() method
e.printStackTrace();
}
// Returning the string builder by
// calling tostring() method
return contentBuilder.toString();
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Custom file path is stored as as string
String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt";
// Calling method 1 to read content of a file
System.out.println(method(filePath));
}
}
Java
// Java Program Illustrating Reading a File to a String
// Using next() and hasNext() method of Scanner class
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
throws IOException
{
// Creating object of Path class where custom local
// directory path is passed as arguments using .of()
// method
Path fileName
= Path.of("C:\\Users\\HP\\Desktop\\gfg.txt");
// Creating an object of Scanner class
Scanner sc = new Scanner(fileName);
// It holds true till there is single element left
// via hasNext() method
while (sc.hasNext()) {
// Iterating over elements in object
System.out.println(sc.next());
}
// Closing scanner class object to avoid errors and
// free up memory space
sc.close();
}
}
输出:
Geeks-for-Geeks
A computer science portal
World's largest technical hub
方法二:使用BufferReader类的readLine()方法
BufferedReader 是一个用于从字符输入流中读取文本的对象。 BufferReader 方法中的readLine() 方法用于一次读取文件一行并返回内容。
句法:
public String readLine()
throws IOException
参数:此方法不接受任何参数。
返回值:此方法返回由此方法读取的字符串,并排除任何可用的终止符号。如果缓冲流已结束并且没有要读取的行,则此方法返回 NULL。
异常:此方法抛出 IO异常 如果发生 I/O 错误。
例子
Java
// Java Program Illustrating Reading a File to a String
// Using readLine() method of BufferReader class
// Importing required classes
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
// MAin class
public class GFG {
// Method 1
// To read file content into the string
// using BufferedReader and FileReader
private static String method(String filePath)
{
// Declaring object of StringBuilder class
StringBuilder builder = new StringBuilder();
// try block to check for exceptions where
// object of BufferedReader class us created
// to read filepath
try (BufferedReader buffer = new BufferedReader(
new FileReader(filePath))) {
String str;
// Condition check via buffer.readLine() method
// holding true upto that the while loop runs
while ((str = buffer.readLine()) != null) {
builder.append(str).append("\n");
}
}
// Catch block to handle the exceptions
catch (IOException e) {
// Print the line number here exception occured
// using printStackTrace() method
e.printStackTrace();
}
// Returing a string
return builder.toString();
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Custom input file path stored in string type
String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt";
// Calling the Method 1 to
// read file to a string
System.out.println(method(filePath));
}
}
输出:
Geeks-for-Geeks
A computer science portal
World's largest technical hub
方法 3:使用 File.readAllBytes() 方法
File.readAllBytes() 方法用于从文件中读取所有字节。该方法确保在读取所有字节或抛出 I/O 错误或其他运行时异常时关闭文件。读取所有字节后,我们将这些字节传递给字符串类构造函数以创建一个字符串。
句法:
public static byte[] ReadAllBytes (string path);
参数:指定打开文件的路径。
方法:
- 声明一个空字符串
- Path 类的get() 方法通过将文件作为参数传递给它来帮助获取文件。
- 现在 File 类的readAllBytes() 方法用于通过传入文件来读取上述文件。
- 最后,打印字符串。
例外:
- ArgumentException:路径是一个零长度的字符串,只包含空格,或者一个或多个由 InvalidPathChars 定义的无效字符。
- ArgumentNullException:路径为空。
- PathTooLongException: 指定的路径、文件名或两者都超过了系统定义的最大长度。
- DirectoryNotFoundException: 指定的路径无效。
- IOException: 打开文件时发生 I/O 错误。
- UnauthorizedAccessException: 当前平台不支持此操作。或者路径指定了一个目录。或者调用者没有所需的权限。
- FileNotFoundException: 找不到路径中指定的文件。
- NotSupportedException:路径格式无效。
- SecurityException: 调用者没有所需的权限。
例子
Java
// Java Program Illustrating Reading a File to a String
// Using File.readAllBytes() method
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
// Main class
public class GFG {
// Method 1
// To read the file content into string with
// Files.readAllBytes(Path path)
private static String method(String file_path)
{
// Declaring an empty string
String str = "";
// Try block to check for exceptions
try {
// Reading all bytes form file and
// storing that in the string
str = new String(
Files.readAllBytes(Paths.get(file_path)));
}
// Catch block to handle the exceptions
catch (IOException e) {
// Print the exception along with line number
// using printStackTrace() method
e.printStackTrace();
}
return str;
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Path is passed from local directory of machine
// and stored in a string
String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt";
// Now call Method1 to
// read the content in above directory
System.out.println(method(filePath));
}
}
输出:
Geeks-for-Geeks
A computer science portal
World's largest technical hub
方法 4:使用 File.lines() 方法
File.lines() 方法用于将文件中的所有行读取到流中。然后使用指定的字符集(如 UTF_8)将文件中的字节解码为字符。
句法:
public static Stream lines(Path path, Charset cs)
throws IOException
参数:它一般需要两个参数:
- 用于解码的字符集。
- 文件的路径。
返回类型:文件中的行作为字符串。
例子
Java
// Java Program Illustrating Reading a File to a String
// Using File.lines() method
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
// Main class
public class GFG {
// Method 1
// To read the file content into the string with -
// Files.lines()
private static String method(String filePath)
{
// Declaring an object of StringBuilder class
StringBuilder contentBuilder = new StringBuilder();
// try block to check for exceptions
// Reading file to string using File.lines() method
// and storing it in an object of Stream class
try (Stream stream
= Files.lines(Paths.get(filePath),
StandardCharsets.UTF_8)) {
stream.forEach(
s -> contentBuilder.append(s).append("\n"));
}
// Catch block to handle the exceptions
catch (IOException e) {
// Print the line number where exception occured
// using printStackTrace() method
e.printStackTrace();
}
// Returning the string builder by
// calling tostring() method
return contentBuilder.toString();
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Custom file path is stored as as string
String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt";
// Calling method 1 to read content of a file
System.out.println(method(filePath));
}
}
输出:
Geeks-for-Geeks
A computer science portal
World's largest technical hub
方法五:使用Scanner类的next()和hasNext()方法
Scanner 类的工作原理是将输入分解为从输入流中顺序检索的令牌。 Scanner 类有两个名为 next() 和 hasNext() 的构建方法。这两种内置方法都返回 String 类型的对象。
例子
Java
// Java Program Illustrating Reading a File to a String
// Using next() and hasNext() method of Scanner class
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
throws IOException
{
// Creating object of Path class where custom local
// directory path is passed as arguments using .of()
// method
Path fileName
= Path.of("C:\\Users\\HP\\Desktop\\gfg.txt");
// Creating an object of Scanner class
Scanner sc = new Scanner(fileName);
// It holds true till there is single element left
// via hasNext() method
while (sc.hasNext()) {
// Iterating over elements in object
System.out.println(sc.next());
}
// Closing scanner class object to avoid errors and
// free up memory space
sc.close();
}
}
输出:
Geeks-for-Geeks
A computer science portal
World's largest technical hub