/*
- Copyright © Huawei Technologies Co., Ltd. 2019-2019. All rights reserved.
*/
package com.huawei.cube.crypto.utils;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import com.huawei.cube.crypto.exception.CryptoException;
import com.huawei.cube.crypto.exception.CryptoExceptionCode;
import static com.huawei.cube.crypto.utils.XmlUtil.file;
import org.wcc.framework.AppRuntimeException;
/**
-
文件工具类
*/
public class FileUtils {/**
- 写入文件,如果文件不存在则创建文件
- @param fileName 要写入的文件名称
- @param content 要写入的内容
- @throws IOException 写入失败抛出io exception
*/
public static void writeFile(String fileName, String content) throws IOException {
Writer bw = fileWriter(fileName);
bw.write(content);
bw.close();
}
/**
-
获取fileWriter,使用完成后需要手动close
-
@param fileName 要写入的文件名称
-
@throws IOException 写入失败抛出io exception
*/
public static Writer fileWriter(String fileName) throws IOException {
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
return bw;
}
/**
-
以字符串的形式读取文件
-
@param fileName 要读取的文件名称
-
@return 文件内容
-
@throws IOException 读取失败报io exception
*/
public static String readFile(String fileName) throws CryptoException, IOException {
File file = new File(fileName);
if (!file.exists()) {
throw CryptoException.of(CryptoExceptionCode.FILE_NOT_EXSIT);
}StringBuilder buffer = new StringBuilder();
InputStream is = new FileInputStream(file.getAbsoluteFile());
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine();
while (line != null) {
buffer.append(line);
buffer.append("\n");
line = reader.readLine();
}
reader.close();
is.close();
return buffer.toString();
}
/**
- 获取文件getInputStream
- @param path 文件路径
- @return 返回 InputStream
- @throws IOException 打开文件异常时抛出
*/
public static BufferedInputStream getInputStream(Path path) throws IOException {
return new BufferedInputStream(Files.newInputStream(path));
}
/**
-
获取文件getInputStream
-
@param path 文件路径
-
@return 返回 InputStream
-
@throws IOException 打开文件异常时抛出
*/
public static BufferedInputStream getInputStream(String path) throws FileNotFoundException, URISyntaxException {return new BufferedInputStream(new FileInputStream(getAbsolutePath(path)));
}
/**
- 根据路径获取文件绝对路径
- @param path 文件路径
- @return
*/
public static String getAbsolutePath(String path) throws URISyntaxException {
return getAbsolutePath(path, (Class) null);
}
/**
-
根据路径获取文件绝对路径
-
@param path
-
@param baseClass
-
@return
*/
public static String getAbsolutePath(String path, Class<?> baseClass) throws URISyntaxException {
String normalPath;
if (path == null) {
normalPath = “”;
} else {
normalPath = normalize(path);
if (isAbsolutePath(normalPath)) {
return normalPath;
}
}URL url = getResource(normalPath, baseClass);
if (null != url) {
return normalize(getDecodedPath(url));
} else {
String classPath = getClassPath();
return null == classPath ? path : normalize(classPath.concat(path));
}
}
public static String getClassPath() throws URISyntaxException {
return getClassPath(false);
}/**
- 得到路径getClassPath
- @param isEncoded
- @return
- @throws URISyntaxException
*/
public static String getClassPath(boolean isEncoded) throws URISyntaxException {
URL classPathURL = getClassPathURL();
String url = isEncoded ? classPathURL.getPath() : getDecodedPath(classPathURL);
return normalize(url);
}
public static URL getClassPathURL() {
return getResourceURL("");
}public static URL getResourceURL(String resource) {
return getResource(resource);
}public static URL getResource(String resource) {
return getResource(resource, (Class) null);
}/**
- 根据路径获取URL
- @param resource
- @param baseClass
- @return
*/
public static URL getResource(String resource, Class<?> baseClass) {
return null != baseClass ? baseClass.getResource(resource) : ClassLoaderUtil.getClassLoader().getResource(resource);
}
public static String getDecodedPath(URL url) throws URISyntaxException {
if (null == url) {
return null;
} else {
String path = toURI(url).getPath();return null != path ? path : url.getPath(); }
}
public static URI toURI(URL url) throws URISyntaxException {
if (null == url) {
return null;
} else {
return url.toURI();
}
}/**
- 判断是否是绝对路径
- @param path
- @return
/
public static boolean isAbsolutePath(String path) {
if (StrUtil.isEmpty(path)) {
return false;
} else {
return ‘/’ == path.charAt(0) || path.matches("1:[/\\].");
}
}
/**
-
设置文件权限
-
(不支持Windows)
-
@param file 文件
-
@param permission 权限的数字组合(如600, 660等),如果为空则不设置权限
-
@param user 文件属主,如果为空则不设置属主
-
@param group 文件属组,如果为空则不设置属组
-
@throws IOException 操作文件失败或执行命令错误抛出异常
*/
public static void setFilePermission(File file, String permission, String user, String group) throws IOException {
if (null == file || PlatformUtil.isWindows()) {
return;
}String encodedfile = encodeForLinux(file.getCanonicalFile().getAbsolutePath());
String chmodCmd = “”;
String chuserCmd = “”;
String chgrpCmd = “”;if (null != permission && !permission.isEmpty()) {
String encodedPermission = encodeForLinux(permission);
String cmd = “chmod PERMISSION FILE”;
cmd = cmd.replace(“PERMISSION”, encodedPermission);
cmd = cmd.replace(“FILE”, encodedfile);
chmodCmd = cmd;
}if (null != user && !user.isEmpty()) {
String encodedUser = encodeForLinux(user);
String cmd = “chown USER FILE”;
cmd = cmd.replace(“USER”, encodedUser);
cmd = cmd.replace(“FILE”, encodedfile);
chuserCmd = cmd;
}if (null != group && !group.isEmpty()) {
String encodedGroup = encodeForLinux(group);
String cmd = “chown :GROUP FILE”;
cmd = cmd.replace(“GROUP”, encodedGroup);
cmd = cmd.replace(“FILE”, encodedfile);
chgrpCmd = cmd;
}String cmd = “”;
if (!chmodCmd.isEmpty()) {
cmd = chmodCmd;
}if (!chuserCmd.isEmpty()) {
if (cmd.isEmpty()) {
cmd = chuserCmd;
} else {
cmd += " && " + chuserCmd;
}
}if (!chgrpCmd.isEmpty()) {
if (cmd.isEmpty()) {
cmd = chgrpCmd;
} else {
cmd += " && " + chgrpCmd;
}
}if (!cmd.isEmpty()) {
Runtime.getRuntime().exec(new String[]{"/bin/sh", “-c”, cmd});
}
}
/**
-
对字符串编码,防止字符串拼接到Linux命令行中导致命令注入
-
具体实现参考了ESAPI的UnixCodec.encodeCharacter(由ESAPI.encoder().encodeForOS)
-
@param s 要编码的字符串
-
@return 编码后的字符串
*/
protected static String encodeForLinux(String s) {
if (null == s) {
return null;
}StringBuffer encoded = new StringBuffer();
char[] charArray = s.toCharArray();
for (char c : charArray) {
if (’-’ == c || isNumber© || isAlphabet©) {
encoded.append©;
} else {
encoded.append("\" + c);
}
}return encoded.toString();
}
/**
- 判断是否是数字
- @param c 字符
- @return 是数字返回true,否则返回false
*/
private static boolean isNumber(char c) {
return c >= ‘0’ && c <= ‘9’;
}
/**
- 判断是否是字母
- @param c 字符
- @return 是字母返回true,否则返回false
*/
private static boolean isAlphabet(char c) {
return c >= ‘a’ && c <= ‘z’ || c >= ‘A’ && c <= ‘Z’;
}
/**
-
获取系统临时目录
-
@return 临时目录
*/
public static String getTempFilePath() {
String os = System.getProperty(“os.name”);
if (null != os && !os.isEmpty() && os.toLowerCase(Locale.ENGLISH).contains(“linux”)) {
return “/tmp/”;
}// 创建临时文件,并获取其路径
File tmpFile = null;
try {
tmpFile = File.createTempFile(“wcc_test”, null);
File parentFile = tmpFile.getParentFile();
if (null == parentFile) {
throw new AppRuntimeException(“does not name a parent directory”);
}
return parentFile.getCanonicalPath() + “/”;
} catch (IOException e) {
throw new AppRuntimeException(“getTmpDir Error”);
} finally {
if (null != tmpFile && tmpFile.exists()) {
tmpFile.delete();
}
}
}
/**
- 判断文件是否存在
- @param path 文件地址
- @return
*/
public static boolean exist(String path) throws URISyntaxException {
return path == null ? false : file(path).exists();
}
/**
-
将path标准化方法
-
@param path
-
@return
*/
public static String normalize(String path) {
if (path == null) {
return null;
} else {
String pathToUse = StrUtil.removePrefixIgnoreCase(path, “classpath:”);
pathToUse = StrUtil.removePrefixIgnoreCase(pathToUse, “file:”);
pathToUse = pathToUse.replaceAll("[/\\]{1,}", “/”).trim();
int prefixIndex = pathToUse.indexOf("?;
String prefix = “”;
if (prefixIndex > -1) {
prefix = pathToUse.substring(0, prefixIndex + 1);
if (StrUtil.startWith(prefix, ‘/’)) {
prefix = prefix.substring(1);
}if (!prefix.contains("/")) { pathToUse = pathToUse.substring(prefixIndex + 1); } else { prefix = ""; } } if (pathToUse.startsWith("/")) { prefix = prefix + "/"; pathToUse = pathToUse.substring(1); } List<String> pathList = StrUtil.split(pathToUse, '/'); List<String> pathElements = new LinkedList(); int tops = 0; for (int i = pathList.size() - 1; i >= 0; --i) { String element = (String) pathList.get(i); if (!".".equals(element)) { if ("..".equals(element)) { ++tops; } else if (tops > 0) { --tops; } else { pathElements.add(0, element); } } } return prefix + CollectionUtil.join(pathElements, "/");
}
}
}
a-zA-Z ↩︎