[英]Ho to read .java file in executable jar
我正在使用此代码加载.java文件并执行搜索:
public class FindClassName {
public static void main(String[] args) {
Logger logger = Logger.getLogger("MOJ.Logger");
try(Scanner scanner = new Scanner(new FileReader("./src/string/FindClassName.java"))){
String pattern = "class\\s*(\\w+)\\s*";
List<String> list = new LinkedList<>();
while(scanner.hasNext()){
String line = scanner.nextLine();
Matcher matcher = Pattern.compile(pattern).matcher(line);
while(matcher.find()){
list.add(matcher.group(1));
}
}
System.out.println(list);
}catch(IOException exception){
logger.info("Couldn't read file");
}
}
static class CHUJ{
}
}
它的工作原理,但当我将其导出到可执行的.jar文件时,它无法将文件加载到阅读器。 我读过我需要使用:
FindClassName.class.getResource("FindClassName.java");
但是这给了我NullPointerException。 我尝试了许多不同的方法,但仍然无法使用getResource()或getResourcesAsStream()将.java文件加载到阅读器。
我知道有很多类似的问题,但我找不到解决方案。
编辑
这很奇怪,这段代码现在运行在可执行jar(包含资源)但不在eclipse中......为什么? 有没有更好的办法?
public class FindClassName {
public static void main(String[] args) throws FileNotFoundException {
Logger logger = Logger.getLogger("MOJ.Logger");
//String directory = "./src/string/FindClassName.java"; //to będzie działać w eclipsie, ale jak zrobisz z tego jar to wszystkie pliki .java zostaną skompilowane na .class
InputStream directory = FindClassName.class.getResourceAsStream("FindClassName.java");
try(Scanner scanner = new Scanner(new InputStreamReader(directory))){
String pattern = "class\\s*(\\w+)\\s*";
List<String> list = new LinkedList<>();
while(scanner.hasNext()){
String line = scanner.nextLine();
Matcher matcher = Pattern.compile(pattern).matcher(line);
while(matcher.find()){
list.add(matcher.group(1));
}
}
System.out.println(list);
}
}
static class CHUJ{
}
}
问题:
当您创建一个可执行的JAR(实际上是任何jar)时,所有.java文件都会被编译并转换为.class文件,然后由JVM使用。
解:
一种解决方案是将源代码目录包含为附加资源目录(不是正常的用例):
<build>
<resources>
<resource>
<directory>${project.build.sourceDirectory}</directory>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
有关使用Eclipse的更多信息或此视频,请参阅此链接
这样的事情应该这样做:
C:\>java -jar JarFileExample.jar
package com.mycompany.myproject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JarFileExample {
public static void main(String[] args) throws Exception {
InputStream is = JarFileExample.class.getResourceAsStream("/com/mycompany/myproject/JarFileExample.java");
writeFileToConsole(is);
}
private static void writeFileToConsole(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
for(String str = reader.readLine(); str != null; str = reader.readLine()) {
System.out.println(str);
}
reader.close();
}
}
C:\>
源代码可以很容易地包含在jar文件中,但取决于您用来创建jar的工具。 我使用了eclipse,基本上是这里描述的方法: Eclipse:在导出为runnable jar时包含源代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.