Java代码如何打开文本文件呢?

书欣 Java经验 发布时间:2023-07-01 22:37:49 阅读数:11292 1
下文笔者将讲述打开文本文件的方法大全
学习完本篇之后,你将彻底掌握打开文本文件的方法,如下所示
打开文本文件 
    使用Files.lines静态方法,即可读取文本文件
      或
    使用FileInputStream读取文件为输入流
	   将输入流转换为字符串或转换为字节数组
例:打开文件
返回文本内容
/**
 * 打开文件,返回其文本内容,可指定编码
 * 
 * @param filePath 文件磁盘路径
 * @param encode   文件编码
 * @return 文件内容
 */
public static String openAsText(String filePath, Charset encode) {
	LOGGER.info("读取文件[{0}]", filePath);

	Path path = Paths.get(filePath);

	try {
		if (Files.isDirectory(path))
			throw new IOException("参数 fullpath:" + filePath + " 不能是目录,请指定文件");
	} catch (IOException e) {
		LOGGER.warning(e);
		return null;
	}

	try {
		StringBuilder sb = new StringBuilder();
		Files.lines(path, encode).forEach(str -> sb.append(str));

		return sb.toString();
	} catch (IOException e) {
		LOGGER.warning(e);
	}

	return null;
}

 
重载方法默认为 UTF-8 编码
当读入的文件的编码是 ANSI 编码
  会报 java.nio.charset.MalformedInputException:Input 异常。

/**
 * 打开文件,返回其文本内容
 * 
 * @param filePath 文件的完全路径
 * @return 文件内容
 */
public static String openAsText(String filePath) {
	return openAsText(filePath, StandardCharsets.UTF_8);
}
 
此方法不适合读取很大的文件,因为可能存在内存空间不足的问题。这时可以试试旧的方式。

/**
 * 旧的方式打开
 * 
 * @param filePath
 * @return
 */
public static String openAsTextOld(String filePath) {
	LOGGER.info("读取文件[{0}]", filePath);

	try {
		return byteStream2string(new FileInputStream(new File(filePath)));
	} catch (FileNotFoundException e) {
		LOGGER.warning(e);
		return null;
	}
}
 
另外有打开文件的 Byte[]

/**
 * 获得指定文件的 byte 数组
 * 
 * @param file 文件对象
 * @return 文件字节数组
 */
public static byte[] openAsByte(File file) {
	try {
		return inputStream2Byte(new FileInputStream(file));
	} catch (FileNotFoundException e) {
		LOGGER.warning(e);
		return null;
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202307/16882223046962.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者