I tried searching how to access a file that wasn't inside a specified package from within a package in Java and was unable to find an answer. Does anyone know how?
3 Answers
If you mean that you want to access a CLASS in the default (unnamed) package from a named package, you can't. The JLS says this:
"A type in an unnamed package (§7.4.2) has no canonical name, so the requirement for a canonical name in every kind of import declaration implies that (a) types in an unnamed package cannot be imported, and (b) static members of types in an unnamed package cannot be imported. As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time error on any attempt to import a type (or static member thereof) in an unnamed package. "
That means that you can't use a single-type import. And a "wildcard" import won't work because you can't name the package.
Yes, you can work around this restriction by using reflection, but it is very cumbersome, and will make your code slow and fragile. If you want to learn about reflection in Java, start here - http://docs.oracle.com/javase/tutorial/reflect/index.html. But is it not a good solution for this "problem".
The correct solution is to use packages ... as the Java language designers intended. The JLS says this:
"Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development."
The implication is that you should only use the / an unnamed package for small / temporary apps (or as a stop gap), and move to using named packages for anything serious.
If you mean that you want to access a FILE (e.g. a resource) in the unnamed package, then you simply need to put a slash on the front of the resource name; e.g.
InputStream is = classLoader.getResourceAsStream("/someresource");