package com.walker.infrastructure.utils;
import com.walker.infrastructure.core.FileNotFoundException;
import com.walker.infrastructure.core.NestedRuntimeException;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
public class FileUtils {
public static final String OS_NAME = "os.name";
public static final String OS_WINDOWS_NAME = "windows";
public static final String FILE_SEPARATOR = "/";
/**
* 缩略图文件名的后缀:_s 表示小图
*/
public static final String THUMB_SUFFIX = "_s";
// private static final String FILE_ROOT_WINDOWS = "file://";
// private static final String FILE_ROOT_UNIX = "file:///";
private static final String FILE_ROOT_WINDOWS = "";
private static final String FILE_ROOT_UNIX = "/";
/**
* 从文件路径中,截取文件ID,文件用id命名。
* @param videoPath 文件绝对路径,如 /opt/ai/video/20220921/landscape_01.mp4 或 d:\demo\movie.jpg
* @return 返回文件名,没有路径和后缀,如: landscape_01 或 movie
*/
public static final String getFileNameWithoutSuffix(String videoPath, String suffix){
// 如果存在windows反斜杠,先转换成正斜杠。2022-10-11
videoPath = videoPath.replaceAll("\\\\", StringUtils.FOLDER_SEPARATOR);
String[] array = videoPath.split(StringUtils.FOLDER_SEPARATOR);
if(array == null || array.length == 0){
System.out.println("文件名称截取id错误:" + videoPath);
return null;
}
String fileName = array[array.length-1];
// String[] idValue = fileName.split(".");
return fileName.replaceAll(suffix, StringUtils.EMPTY_STRING);
}
/**
* 返回文件路径地址中的路径部分,如: d:/demo/file.txt --> d:/demo/
* @param url
* @return
* @date 2023-02-15
*/
public static final String getFilePathWithoutName(String url){
if(StringUtils.isEmpty(url)){
return null;
}
int lastSeparatorIndex = url.lastIndexOf(StringUtils.FOLDER_SEPARATOR);
if(lastSeparatorIndex < 0){
System.out.println("url中不包含文件路径:" + url);
return null;
}
return url.substring(0, lastSeparatorIndex);
}
/**
* 返回路径中文件名,如: d:/demo/file.txt --> file.txt
* @param url
* @return
*/
public static final String getFileNameWithoutPath(String url){
int fileNameIndex = url.lastIndexOf(StringUtils.FOLDER_SEPARATOR) + 1;
if(fileNameIndex < 0){
System.out.println("url中不包含文件路径:" + url);
return null;
}
return url.substring(fileNameIndex, url.length());
}
/**
* 文件夹或文件是否存在。
* @param fileOrFolder 文件(或文件夹)绝对路径
* @return
* @date 2022-10-11
*/
public static final boolean isExist(String fileOrFolder){
if(StringUtils.isEmpty(fileOrFolder)){
return false;
}
File file = new File(fileOrFolder);
return file.exists();
}
public static final boolean isWindows(){
String osName = System.getProperty(OS_NAME);
if(osName != null && osName.toLowerCase().indexOf(OS_WINDOWS_NAME) >= 0){
return true;
}
return false;
}
public static final String getFileSystemRoot(){
if(isWindows()){
return FILE_ROOT_WINDOWS;
} else
return FILE_ROOT_UNIX;
}
/**
* 检查目录,如果不存在将会创建新目录,包括子目录。
* @param path
*/
public static final void checkDir(String path){
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
}
private static final String FILE_EXT_SEPARATOR = ".";
/**
* 返回文件名的扩展名,如果不存在返回null
,如: txt
* @param filename
* @return
*/
public static final String getFileExt(String filename){
int extIndex = filename.lastIndexOf(FILE_EXT_SEPARATOR);
if(extIndex > 0){
// filename.txt
return filename.substring(extIndex + 1);
}
return null;
}
/**
* 返回文件字节信息,通常适用于读取较小文件。
* @param file
* @return
*/
public static final byte[] getFileBytes(File file){
assert (file != null);
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
// int byteCount = 0;
byte[] buffer = new byte[in.available()];
// int bytesRead = -1;
// while ((bytesRead = in.read(buffer)) != -1) {
// byteCount += bytesRead;
// }
in.read(buffer, 0, buffer.length);
return buffer;
} catch (java.io.FileNotFoundException e) {
throw new FileNotFoundException();
} catch(IOException ioe){
throw new NestedRuntimeException(null, ioe);
} finally {
if(in != null){
try {
in.close();
} catch (IOException e) {}
}
}
}
/**
* 读文本内容,按行读取,返回集合。
* @param filePath 文件绝对路径
* @return
*/
public static List getFileLines(String filePath){
File file = new File(filePath);
if(!file.exists()){
System.out.println("文件不存在,无法读取内容:" + filePath);
return null;
}
// String encoding = "utf-8";
List content = new ArrayList<>(64);
try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), StringUtils.DEFAULT_CHARSET_UTF8);
BufferedReader bufferedReader = new BufferedReader(read)) {
//判断文件是否存在
if (file.isFile() && file.exists()) {
String lineTxt;
while ((lineTxt = bufferedReader.readLine()) != null) {
// System.out.println(lineTxt);
content.add(lineTxt);
}
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("读取文件内容出错");
}
return content;
}
public static final void writeFile(byte[] content, String filename){
throw new UnsupportedOperationException();
}
/**
* 删除一个文件
* @param file 文件(不能是目录)
* @return
*/
public static final boolean deleteFile(File file){
if(file != null){
try{
if(file.isDirectory()){
throw new UnsupportedOperationException("File must be not a directory!");
}
return file.delete();
} catch(Exception e){
throw new NestedRuntimeException(null, e);
}
}
return false;
}
/**
* 把字符串内容写入到一个文件中。
* @param content
* @param fileName
* @return
* @throws Exception
*/
public static boolean writeTxtFile(String content,File fileName)throws Exception{
RandomAccessFile mm=null;
boolean flag=false;
// FileOutputStream o=null;
try {
// o = new FileOutputStream(fileName);
// o.write(content.getBytes("GBK"));
// o.close();
mm=new RandomAccessFile(fileName,"rw");
mm.writeBytes(content);
flag=true;
} catch (java.io.FileNotFoundException e) {
throw new FileNotFoundException("not found file: " + fileName, e);
}finally{
if(mm!=null){
mm.close();
}
}
return flag;
}
/**
* 创建空文件
* @param filepath
* @throws IOException
*/
public static final void createEmptyFile(String filepath) throws IOException{
File file = new File(filepath);
if(!file.exists()){
file.createNewFile();
} else
System.out.println("file exist: " + filepath);
}
/**
* 给定文件相对路径,返回缩略图路径,如:2014/3/aaa_123456_s.jpg
* @param path
* @param ext
* @return
*/
@Deprecated
public static final String getThumbNailsName(String path, String ext){
StringBuilder thumb = new StringBuilder();
thumb.append(path.subSequence(0, path.lastIndexOf(StringUtils.SYMBOL_DOT)));
thumb.append("_s.").append(ext);
return thumb.toString();
}
/**
* 给定文件相对路径,返回缩略图路径,如:2014/3/aaa_123456_s.jpg
* @param path
* @return
*/
public static final String getThumbNailsName(String path){
StringBuilder thumb = new StringBuilder();
thumb.append(path.subSequence(0, path.lastIndexOf(StringUtils.SYMBOL_DOT)));
thumb.append("_s.").append(FileUtils.getFileExt(path));
return thumb.toString();
}
public static void main(String[] args){
// System.out.println(FileUtils.getFileExt("myfile.txt"));
// System.out.println(FileUtils.getFileExt("myfile-111.2012.txt"));
// System.out.println(FileUtils.getFileExt("myfiletxt"));
// System.out.println("file: " + FileUtils.getFileBytes(new File("d:/sso-1.jpg")));
// System.out.println(getThumbNailsName("2014/3/aaa_123456.jpg"));
// System.out.println(getFileExt("d:/test/demo.jpg"));
System.out.println(getFilePathWithoutName("d:/test/demo.jpg"));
System.out.println(getFileNameWithoutPath("d:/test/demo.jpg"));
}
}