Get Java Source File Package
My goal is to find the package (as string) of a Java source file, specified as plain text and not sorted in folders.
I can't just find the first instance of the keyword package
in the file, because it might appear inside a comment. So I thought of two alternatives:
- Scan file by word, save "in-comment" flag for scanner. The first time a keyword
package
is not found in a comment, stop scanning and report the result. - Using a regex - should be theoretically possible because block comments are not followed in Java, but I tried to make a regex like this and it turned out to be quite complicated - for me at least.
Another difference between the two approaches is that with manual crawling I can stop crawling when I can be sure the keyword is package
no longer displayed, keeping it for a while ... and I am not sure if I can do something similar to regular expressions. On the other hand, the "when it can't appear anymore" solution is not necessarily straightforward , although I could use several heuristics for that.
I would love to hear any input on this issue and would welcome any help with regex. My solution is written in Java as well.
EDIT: For those suggesting actually parsing a file, this is definitely a viable option, thanks, but it seems too hard to parse the whole file just for the package. I will do this if there is no simpler alternative.
a source to share
I solved this problem using a java parser. For my purpose, javaparser was the best fit.
CompilationUnit cu = JavaParser.parse( file );
String packageName = cu.getPackage().getName().toString();
a source to share
You can use an actual java parser like javaparser . It gives a properly parsed java file without having to reinvent the Java parser or use a bad man's parser (regex.)
The only drawback I can see is that perhaps you want to stop parsing as soon as you find the package, and don't parse the rest of the file. There are various, somewhat hacky ways you could achieve this, but I recommend that you do all the file work before thinking about it.
a source to share