需求:通过java代码去获取src下中某个文件夹的所有properties或者txt文件,文件个数不确定。要保证能将该工程打成jar文件后能正常获取。
参考解决方案:https://www.cnblogs.com/googlemeoften/p/4827402.html
一、通过JarFile这个类读取内容,获得所有的文件的名字
JarFile jarFile = new JarFile(filePath);
Enumeration<JarEntry> entries = jarFile.entries();
//存放所有的文件名称
ArrayList<String> fileNames=new ArrayList<>();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
//对文件进行限定处理,取得自己想要的文件
if (!entry.isDirectory() && entryName.startsWith("resource/Ta") && entryName.endsWith(".txt")) {
fileNames.add(entryName);
}
}
注意filePath的写法:
//比如我的jar文件输出到d盘,这里的filePath是D:\/DPFSP9.jar
//我的linux目录是/usr/java,注意下面的DPFSP9.jar前面的 /,所以filePath变成了/usr/java/DPFSP9.jar
//这么写是为了通用性
String filePath=System.getProperty("user.dir")+"/DPFSP9.jar";
二、获得具体的一个文件
以下只给出关键代码:因为我上一步获取的entryName是 resource/Ta031_2.txt for(String fileName:fileNames){
//注意这里对文件名的处理,相当于绝对定位了
String str = "/"+fileName;
//根据这里的字符串获取流
InputStream is=this.getClass().getResourceAsStream(str);
BufferedReader br=new BufferedReader(new InputStreamReader(is));
}
注意注意注意自行关闭流
三、输出文件
https://www.cnblogs.com/XiOrang/p/5652875.html
以下是创建文件部分代码,打包运行之后,文件输出位置和jar同属一个目录。
private static String path = System.getProperty("user.dir")+"/";
public static String createFile(String fileName){
Boolean bool = false;
filenameTemp = path+fileName+".txt";//文件路径+名称+文件类型
File file = new File(filenameTemp);
try {
//如果文件不存在,则创建新的文件
if(!file.exists()){
file.createNewFile();
bool = true;
System.out.println("success create file,the file is "+filenameTemp);
}
} catch (Exception e) {
e.printStackTrace();
}
return filenameTemp;
}