com.haoxuer.discover.web.utils.FileUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of discover-website Show documentation
Show all versions of discover-website Show documentation
discover网站配置模块,主要管理网站主题,网站配置等功能
package com.haoxuer.discover.web.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* 文件工具类
*
* @author 张浩伟
* @version 1.01 2017年08月30日
*/
public class FileUtils {
public static class FileTree {
/**
* name
*/
public String name;
/**
* path
*/
public String path;
/**
* open
*/
public Boolean open;
/**
* dir是否是文件夹
*/
public Boolean dir;
/**
* children
*/
public List children;
/**
* 更新时间
*/
public Long lastTime;
}
public static List getTree(String path, String parent) {
List result = new ArrayList();
List childs = new ArrayList();
File file = new File(path);
FileTree tree = new FileTree();
tree.name = file.getName();
tree.open = false;
tree.path = parent;
tree.dir = false;
if (file.isDirectory()) {
tree.dir = true;
File[] listFiles = file.listFiles();
if (listFiles == null) {
return result;
}
for (File listFile : listFiles) {
FileTree child = new FileTree();
child.name = listFile.getName();
child.open = false;
child.path = parent + "/" + listFile.getName();
child.lastTime = listFile.lastModified();
if (listFile.isDirectory()) {
System.out.println("path = " + path + "/" + child.name + " parent = " + child.path);
childs.addAll(getTree(path + "/" + child.name, child.path));
child.dir = true;
} else {
childs.add(child);
child.dir = false;
}
}
tree.children = childs;
}
result.add(tree);
return result;
}
/**
* 读取文件
*
* @param path 文件路径
* @return
*/
public static String readFile(String path) {
StringBuilder result = new StringBuilder();
try {
File file = new File(path);
BufferedReader br = new BufferedReader(new FileReader(file));
String s = null;
while ((s = br.readLine()) != null) {
result.append(System.lineSeparator()).append(s);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
/**
* 保存文件
*
* @param path 路径
* @return
*/
public static boolean saveFile(String path, String content) {
File file = new File(path);
try {
FileWriter fw = new FileWriter(file, false);
fw.write(content);
fw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private static List allFile = new ArrayList<>();
public static List fileList(File file) {
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
for (File listFile : listFiles) {
String newDir = file.getPath() + "/" + listFile.getName();
File readfile = new File(newDir);
if (readfile.isDirectory()) {
fileList(readfile);
} else {
String fileName = readfile.getPath();
allFile.add(fileName);
}
}
} else {
String fileName = file.getPath();
allFile.add(fileName);
}
return allFile;
}
}