简体   繁体   中英

Keeping Java files in packages during compilation

In my Java class, I would like to output the code of another (uncompiled) Java class of the same project. This is the package structure:

main (package)
   files (package)
      SampleClass.java
      SampleFile.txt
CodeOutput.java

And the code of CodeOutput.java :

public class CodeOutput {
    public void run() {
        InputStream in = getClass().getResourceAsStream("files/SampleClass.java");
        BufferedReader stream = new BufferedReader(new InputStreamReader(in));

        try {
            System.out.println(stream.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new CodeOutput().run();
    }
}

I try to load the file SampleClass.java from the files package and output its first line. However, the Java file doesn't remain in the package after compilation. I also tried to exclude the file from the build path (in the file's context menu: Build Path -> Exclude), so the code isn't compiled to a .class file, but still the Java file doesn't appear in the package. It works fine with the SampleFile.txt , so I'm sure it has something to do with the project/build path settings.

Any ideas how to treat Java files like other resources in a package?

Eclipse will compile all .java files under src/main/java . If you wish not to compile a java file, keep it under /src/main/resources . Also if you're using maven to build your source code, you can easily include source code in the jar file. Instructions here

Create a new directory outside your java source and add that directory to your class path. You can create the same package structure under that directory. So CodeOutput would be a compilable java class, but all files added under the new directory in your class path will not.

If you don't want to do that, you cannot access ur source files the way ur trying to access them now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM