Java根据路径获取文件内容

时间:2022-12-01 15:52:59

文章目录

给出一个资源路径、然后获取资源文件信息,常见三种方式:①网络地址 ②本地绝对路径 ③本地相对路径

一、思路

首先,给出一个string表示资源文件的标识,如何判断是网络中的文件还是本地的文件?

*http开头的可以看成是网络文件
*其余的可看成本地文件

对于mac和linux系统而言:

*以 / 和 ~ 开头的表示绝对路径

*其他的看做是相对路径

对于windows系统而言,绝对路径形如c:\test.text

*路径中包含 : 看成是绝对路径

*以 \ 开头看做的绝对路径

二、实现

判断操作系统:

/**
* 是否windows系统
*/
public static boolean isWinOS() {
boolean isWinOS = false;
try {
String osName = System.getProperty("os.name").toLowerCase();
String sharpOsName = osName.replaceAll("windows", "{windows}").replaceAll("^win([^a-z])", "{windows}$1")
.replaceAll("([^a-z])win([^a-z])", "$1{windows}$2");
isWinOS = sharpOsName.contains("{windows}");
} catch (Exception e) {
e.printStackTrace();
}
return isWinOS;
}

绝对路径与否判断:

public static boolean isAbsFile(String fileName) {
if (OSUtil.isWinOS()) {
// windows 操作系统时,绝对地址形如 c:\descktop
return fileName.contains(":") || fileName.startsWith("\\");
} else {
// mac or linux
return fileName.startsWith("/");
}
} /**
* 将用户目录下地址~/xxx 转换为绝对地址
*
* @param path
* @return
*/
public static String parseHomeDir2AbsDir(String path) {
String homeDir = System.getProperties().getProperty("user.home");
return StringUtils.replace(path, "~", homeDir);
}

文件获取封装类:

public static InputStream getStreamByFileName(String fileName) throws IOException {
if (fileName == null) {
throw new IllegalArgumentException("fileName should not be null!");
} if (fileName.startsWith("http")) {
// 网络地址
return HttpUtil.downFile(fileName);
} else if (BasicFileUtil.isAbsFile(fileName)) {
// 绝对路径
Path path = Paths.get(fileName);
return Files.newInputStream(path);
} else if (fileName.startsWith("~")) {
// 用户目录下的绝对路径文件
fileName = BasicFileUtil.parseHomeDir2AbsDir(fileName);
return Files.newInputStream(Paths.get(fileName));
} else { // 相对路径
return FileReadUtil.class.getClassLoader().getResourceAsStream(fileName);
}
}

原文地址:

灰灰blog