0

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?

1
  • Do you mean that the file is not in the same package as the class you're executing, or that the file is in no package whatsoever? Commented Dec 30, 2012 at 0:20

3 Answers 3

1

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");
Sign up to request clarification or add additional context in comments.

Comments

0

You cannot without reflection.

Use of the 'default package' (no package at all) is really discouraged, and this is one of the things that exists to discourage it.

Comments

0

The "default" package actually is the root directory. Use absolute paths:

URL url = getClass().getResource("/myphoto.jpg");
InputStream in = getClass().getResourceAsStream("/myphoto.jpg");

Open the created jar with 7zip/WinZip or the like. You should see the file in the root directory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.