Java8 file tool class FileUtils (continuously updated)

1. Java8 file processing

Use the Java8 java.nio.filemethod for file processing.

1.1. Reading files

All content is read out at once, and the result is a string.

1.1.1. Code

	/**
	 * 读取文件
	 *
	 * @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. Calling

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

The file path is generally represented 正斜杠 “/”by , which can better adapt to Windows and Linus systems.

1.1.3. Running results

insert image description here
insert image description here

1.1.4. The file path uses an absolute path

Files can be read using absolute addresses. However, in the project, try not to use the absolute address to read the file, because the installation path may change when the project goes online.

Here's an example of using an absolute path:

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

insert image description here

2. File tools

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 "";
		}
	}

}

Guess you like

Origin blog.csdn.net/sgx1825192/article/details/132118571