有時在處理文件時,我們需要在Java中將文件讀取為字符串。今天我們將研究在Java中將文件讀取為字符串的各種方法。
Java讀取文件為字符串
在Java中讀取文件為字符串有許多方法。在本教程中,我們將探索以下方法。
- 使用BufferedReader在Java中將文件讀取為字符串
- 使用FileInputStream在Java中將文件讀取為字符串
- 使用Files類在Java中將文件讀取為字符串
- 使用Scanner類將文件讀取為字符串
- 使用Apache Commons IO FileUtils類在Java中將文件讀取為字符串
現在讓我們深入研究這些類並將文件讀取為字符串。
使用BufferedReader在Java中將文件讀取為字符串
我們可以使用BufferedReader
的readLine
方法逐行讀取文件。我們只需將這些行附加到一個StringBuilder對象,並包含換行字符。以下是使用BufferedReader將文件讀取為字符串的代碼片段。
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
// 刪除最後的換行分隔符
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
reader.close();
String content = stringBuilder.toString();
還有一種高效的方式使用BufferedReader和字符數組將文件讀取為字符串。
BufferedReader reader = new BufferedReader(new FileReader(fileName));
StringBuilder stringBuilder = new StringBuilder();
char[] buffer = new char[10];
while (reader.read(buffer) != -1) {
stringBuilder.append(new String(buffer));
buffer = new char[10];
}
reader.close();
String content = stringBuilder.toString();
使用FileInputStream在Java中將文件讀取為字符串
我們可以使用FileInputStream和字節數組將文件讀取為字符串。您應該使用此方法來讀取非基於字符的文件,例如圖片、視頻等。
FileInputStream fis = new FileInputStream(fileName);
byte[] buffer = new byte[10];
StringBuilder sb = new StringBuilder();
while (fis.read(buffer) != -1) {
sb.append(new String(buffer));
buffer = new byte[10];
}
fis.close();
String content = sb.toString();
使用Files類在Java中將文件讀取為字符串
我們可以使用Files實用程序類在單行代碼中將所有文件內容讀取為字符串。
String content = new String(Files.readAllBytes(Paths.get(fileName)));
使用Scanner类将文件读取为字符串
Scanner类是在Java中将文本文件快速读取为字符串的一种方式。
Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name());
String content = scanner.useDelimiter("\\A").next();
scanner.close();
使用Apache Commons IO FileUtils类将Java读取文件为字符串
如果在项目中使用Apache Commons IO,那么这是在Java中将文件快速读取为字符串的简单方式。
String content = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8);
Java读取文件为字符串示例
这是带有适当异常处理的最终程序,展示了将文件读取为字符串的所有不同方式。
package com.journaldev.files;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
public class JavaReadFileToString {
/**
* This class shows different ways to read complete file contents to String
*
* @param args
* @throws IOException
*/
public static void main(String[] args) {
String fileName = "/Users/pankaj/Downloads/myfile.txt";
String contents = readUsingScanner(fileName);
System.out.println("*****Read File to String Using Scanner*****\n" + contents);
contents = readUsingApacheCommonsIO(fileName);
System.out.println("*****Read File to String Using Apache Commons IO FileUtils*****\n" + contents);
contents = readUsingFiles(fileName);
System.out.println("*****Read File to String Using Files Class*****\n" + contents);
contents = readUsingBufferedReader(fileName);
System.out.println("*****Read File to String Using BufferedReader*****\n" + contents);
contents = readUsingBufferedReaderCharArray(fileName);
System.out.println("*****Read File to String Using BufferedReader and char array*****\n" + contents);
contents = readUsingFileInputStream(fileName);
System.out.println("*****Read File to String Using FileInputStream*****\n" + contents);
}
private static String readUsingBufferedReaderCharArray(String fileName) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
char[] buffer = new char[10];
try {
reader = new BufferedReader(new FileReader(fileName));
while (reader.read(buffer) != -1) {
stringBuilder.append(new String(buffer));
buffer = new char[10];
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
private static String readUsingFileInputStream(String fileName) {
FileInputStream fis = null;
byte[] buffer = new byte[10];
StringBuilder sb = new StringBuilder();
try {
fis = new FileInputStream(fileName);
while (fis.read(buffer) != -1) {
sb.append(new String(buffer));
buffer = new byte[10];
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
private static String readUsingBufferedReader(String fileName) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null;
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
// 删除最后一个ls
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
private static String readUsingFiles(String fileName) {
try {
return new String(Files.readAllBytes(Paths.get(fileName)));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static String readUsingApacheCommonsIO(String fileName) {
try {
return FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static String readUsingScanner(String fileName) {
Scanner scanner = null;
try {
scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name());
// 我们可以使用分隔符正则表达式 "\\A"、"\\Z"或"\\z"
String data = scanner.useDelimiter("\\A").next();
return data;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (scanner != null)
scanner.close();
}
}
}
您可以使用以上任何一种方式在Java中将文件内容读取为字符串。但是,如果文件大小很大,不建议使用,因为可能会遇到内存不足错误。
你可以從我們的GitHub存儲庫中查看更多Java IO示例。
參考:
Source:
https://www.digitalocean.com/community/tutorials/java-read-file-to-string