Java8 文件工具类 FileUtils(持续更新中)

1. Java8 文件处理

使用 Java8 的 java.nio.file 方法,来进行文件处理。

1.1. 读文件

所有内容一次读出来,结果为字符串。

1.1.1. 代码

	/**
	 * 读取文件
	 *
	 * @param path 文件路径
	 * @return 文件内容(字符串)
	 */
	public static String read(String path) {
    
    
		try {
    
    
			return Files.readString(Paths.get(path));
		} catch (IOException e) {
    
    
			e.printStackTrace();
			return "";
		}
	}

1.1.2. 调用

	// 文件放在项目根目录下的 config 目录下,此处填写的是相对路径
	String json = FileUtils.read("config/user.json");
	System.out.println(json);

文件路径,一般采用 正斜杠 “/” 来表示,能更好的适配 Windows 和 Linus 系统。

1.1.3. 运行结果

在这里插入图片描述
在这里插入图片描述

1.1.4. 文件路径使用绝对路径

文件是可以使用绝对地址来读取的。但是,在项目中,尽量不要采用绝对地址的方式来读取文件,因为项目上线时的安装路径是可能变化的。

下面给出一个使用绝对路径的例子:

	String json = FileUtils.read("F:/open-source/spring-demo/GsonDemo/config/user.json");
	System.out.println(json);

在这里插入图片描述

2. 文件工具类

package com.example.util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileUtils {
    
    

	/**
	 * 读取文件
	 *
	 * @param path 文件路径
	 * @return 文件内容(字符串)
	 */
	public static String read(String path) {
    
    
		try {
    
    
			return Files.readString(Paths.get(path));
		} catch (IOException e) {
    
    
			e.printStackTrace();
			return "";
		}
	}

}

猜你喜欢

转载自blog.csdn.net/sgx1825192/article/details/132118571
今日推荐