文件操作,异步非阻塞I/O
java封装了很棒且很完美的文件系统操作详情请移步https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
package com.miku.common.support;
import org.springframework.util.ClassUtils;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 文件操作
* java封装了很棒且很完美的文件系统操作
*
* @see java.nio.file.Files
* @see java.nio.file.Paths
*
* @author:panw.
* @date:2018/4/7.
*
* @since jdk:1.8
* @since spring:2.5
*/
public final class File {
private File () {}
private static final String CHARSET = "UTF-8";
/**
* 获取文件系统绝对路径
* <p>{@link org.springframework.util.ClassUtils#getDefaultClassLoader}</p>
* <p>{@link java.lang.ClassLoader#getResource}</p>
*
* @param path
* @return
* @throws IOException
*/
public static String getSysPath(String path) throws IOException {
//你家文件系统命名还有classpath:?(黑人问号),如果有请切割字符串前10位对比
if (path.contains("classpath:")) {
int i = path.indexOf(":");
String contextPaht = path.substring(i + 1);
URL url = ClassUtils.getDefaultClassLoader().getResource(contextPaht);
return url == null ? null : url.getPath();
}
return path;
}
/**
* 读取文件内容
* <p>{@link #isContextPath}</p>
* <p>{@link #getSysPath}</p>
* <p>注意:直接调用之后需要关闭Stream操作,详情请看{@link java.nio.file.Files#lines}</p>
*
* @param path
* @return
* @throws IOException
*/
public static Stream<String> getContent(String path) throws IOException {
if (isContextPath(path)) {
path = getSysPath(path);
}
return Files.lines(Paths.get(path), Charset.forName(CHARSET));
}
/**
* 读取文件内容
* <p>{@link #getContent}</p>
*
* @param path
* @return
* @throws IOException
*/
public static String getContentToString(String path) throws IOException {
return getContent(path).collect(Collectors.joining("\n"));
}
/**
* 替换文件内容
*
* <p>{@link #getContent}</p>
* <p>{@link java.nio.file.Files#write}</p>
*
* @param path
* @param regex
* @param replacement
* @return
* @throws IOException
*/
public static void replacedContent(String path,String regex,String replacement) throws IOException {
List<String> replaced = getContent(path)
.map(line -> line.replaceAll(regex, replacement))
.collect(Collectors.toList());
Files.write(Paths.get(path), replaced,Charset.forName(CHARSET));
}
/**
* 判断路径是否是classpath
*
* @param path
* @return
*/
public static final boolean isContextPath(String path) {
if (path.contains("classpath:")) {
return true;
}
return false;
}
}
不适合大文件读写,如有需要请联系。
结语:如有觉得不够力,不够用的请留言注明!!
博客原创:写作不易,转载请标明出处。文章地址:[文章地址]