java 根据路径和内容生成文件_Java根据路径获取文件内容

一、思路

首先,给出一个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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值