将Java读取文件并转换为字符串

有时在处理文件时,我们需要将文件读取为Java中的字符串。今天我们将探讨多种将文件读取为字符串的方法。

将Java中读取文件并转换为字符串的操作。

在Java中,有许多将文件读取为字符串的方法。在本教程中,我们将探讨以下几种方法。

    1. 使用BufferedReader将Java文件读取为字符串

 

    1. 使用FileInputStream将文件读取为Java字符串

 

    1. 使用Files类将Java文件读取为字符串

 

    1. 使用Scanner类将文件读取为字符串

 

    使用Apache Commons IO FileUtils类将Java文件读取为字符串
java read file to string

使用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);
}
// delete the last new line separator
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.Olivia.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/scdev/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);
			}
			// delete the last 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());
			// we can use Delimiter regex as "\\A", "\\Z" or "\\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示例。

参考文献:

  • BufferedReader API Doc
  • Files API Doc
发表回复 0

Your email address will not be published. Required fields are marked *


广告
将在 10 秒后关闭
bannerAds