62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
public class FileOutClasses {
public static void main(String[] args) throws Exception {
// File file = new File("../../log4j.properties");//找不到文件
InputStream is = new FileInputStream(
"../../log4j.properties");//找不到文件
// InputStream is = FileOutClasses.class
// .getResourceAsStream("../../log4j.properties");
// 这里用getResouceAsStream可以用相对路径,而new File用相对路径却找不到文件,为什么呢?
}
}
问题如下:
1. 文件log4j.properties放在classes目录外面时,只能用绝对路径访问,不能用相对路径。怎样才能使用相对路径呢?
2. 即时log4j.properties放在classes目录里面
A.又出现下面两个问题:当new File时也不能用相对路径 ;
B.要得到一个InputStream ,使用new FileInputStream()也不能用相对路径。但是用getResourceAsStream()却可以用相对路径,这是为什么呢?二者有何区别?
*
public static String findLocalPath(Class clazz, String resourceName) {
String originalPath = clazz.getResource(resourceName).toString();
return prune(originalPath);
}
private static String prune(String source) {
String prefix = "jar:";
if (source == null || source.isEmpty()) {
return source;
}
StringBuilder buff = new StringBuilder(source);
int index = 0;
if (buff.indexOf(prefix) != -1) {
buff.delete(0, prefix.length());//去除开头的"jar:"字串。
index = buff.lastIndexOf(".jar");
buff.delete(index, buff.length());//此时文件名一定是.jar结束,删除从.之后的所有字符。
}
//buff.delete(0, "file:".length());
index = buff.lastIndexOf("/");
buff.delete(index, buff.length());//去掉文件名。
return buff.toString();
}
public class Main {
public static void main(String[] args) {
String localPath = findLocalPath(Main.class,"/flag");
System.out.println(localPath);
}
}
String folder =FileOutClasses.class.getClassLoader().getResource("log4j.properties").toString();
folder = folder.replace("%20"," ");
folder = folder.replace("file:/","");
InputStream ips = new BufferedInputStream(new FileInputStream(folder));