简体   繁体   English

在编译过程中将Java文件保留在包中

[英]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. 在我的Java类中,我想输出同一项目的另一个(未编译)Java类的代码。 This is the package structure: 这是包的结构:

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

And the code of CodeOutput.java : 以及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. 我尝试从files包中加载文件SampleClass.java并输出其第一行。 However, the Java file doesn't remain in the package after compilation. 但是,编译后Java文件不会保留在软件包中。 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. 我还尝试从构建路径中排除文件(在文件的上下文菜单中:Build Path-> Exclude),因此代码未编译为.class文件,但Java文件仍未出现在包中。 It works fine with the SampleFile.txt , so I'm sure it has something to do with the project/build path settings. 它可以与SampleFile.txt一起正常工作,因此我确定它与项目/构建路径设置有关。

Any ideas how to treat Java files like other resources in a package? 有什么想法可以像对待包中的其他资源一样对待Java文件吗?

Eclipse will compile all .java files under src/main/java . Eclipse将在src/main/java下编译所有.java文件。 If you wish not to compile a java file, keep it under /src/main/resources . 如果您不想编译Java文件,请将其保存在/src/main/resources Also if you're using maven to build your source code, you can easily include source code in the jar file. 另外,如果您使用Maven来构建源代码,则可以轻松地在jar文件中包含源代码。 Instructions here 这里的说明

Create a new directory outside your java source and add that directory to your class path. 在Java源代码之外创建一个新目录,并将该目录添加到类路径中。 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. 所以CodeOutput将是一个可编译的Java类,但是添加到您的类路径中新目录下的所有文件都不会。

If you don't want to do that, you cannot access ur source files the way ur trying to access them now. 如果您不想这样做,则无法以您现在尝试访问它们的方式访问您的源文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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