分享我的两个工具类
- 新增 LjfUtils 类,提供操作系统判断方法
- 新增 PathUtils 类,实现路径获取和文件读取功能
public class LjfUtils {
public static boolean isRunInWindows(){
return System.getProperty("os.name").toLowerCase().startsWith("win");
}
public static boolean isRunInLinux(){
return System.getProperty("os.name").toLowerCase().startsWith("linux");
}
public static boolean isRunInIDEA() {
try {
Class.forName("com.intellij.rt.execution.application.AppMainV2");
return true;
} catch (ClassNotFoundException ignored) {
return false;
}
}
}
public class PathUtils {
public static String getJarPath() {
String path = PathUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
int begIndex = 0;
int endIndex = 0;
if (LjfUtils.isRunInIDEA()) {
path = path.substring(1);
endIndex = path.lastIndexOf("/");
} else if (LjfUtils.isRunInLinux()) {
begIndex = 5;
endIndex = path.indexOf("!");
path = path.substring(0, endIndex);
endIndex = path.lastIndexOf("/");
} else if (LjfUtils.isRunInWindows()) {
begIndex = 6;
endIndex = path.indexOf("!");
path = path.substring(0, endIndex);
endIndex = path.lastIndexOf("/");
}
path = path.substring(begIndex, endIndex)+"/";
try {
path = java.net.URLDecoder.decode(path, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return path;
}
public static void getResource(String fileName) {
InputStream in = PathUtils.class.getClassLoader().getResourceAsStream(fileName);
printFileContent(in);
}
public static void printFileContent(Object obj) {
if (null == obj) {
throw new RuntimeException("参数为空");
}
BufferedReader reader = null;
try {
if (obj instanceof String) {
reader = new BufferedReader(new FileReader(new File((String) obj)));
} else if (obj instanceof InputStream) {
reader = new BufferedReader(new InputStreamReader((InputStream) obj));
}
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}