如何使用基本的Gradle项目正确引用资源?

时间:2015-12-07 22:10:29

标签: java eclipse gradle resources

我有以下(粗略)Gradle项目布局(在Eclipse项目中):

src/
 main/
  java/
   example/
    TextTransformer.java
  resources/
    transformMe.txt

 build.gradle

粗略地说,build.gradle看起来像

apply plugin: 'java'
apply plugin: 'eclipse'

sourceCompatibility = 1.7
targetCompatibility = 1.7
version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Some API',
                   'Implementation-Version': version
    }
}

repositories {
    mavenCentral()
}

dependencies {
    ...
}

uploadArchives {
    repositories {
       flatDir {
           dirs 'repos'
       }
    }
}

在TextTransform.java中,我看起来像:

    Reader  reader      = new FileReader("/transformMe.txt");
    Writer  writer      = new StringWriter();
    new UglifyJsProcessor().process(reader, writer);
    String  str         = writer.toString();

我无法阅读transformMe.txt。我还试过FileReader("transfomMe.txt");和其他一些变体。我做错了什么?

1 个答案:

答案 0 :(得分:2)

听起来您只想从JAR资源中读取文件:

InputStream input = ClassLoader.class.getResourceAsStream("/transformMe.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));

new UglifyJsProcessor().process(...);