jarとして実行しているときにクラスパスリソースが見つかりません


128

Spring Boot 1.1.5と1.1.6の両方でこの問題が発生しています。@ Valueアノテーションを使用してクラスパスリソースをロードしています。これは、STS(3.6.0、Windows)内からアプリケーションを実行するとうまく機能します。しかし、mvnパッケージを実行してからjarを実行しようとすると、FileNotFound例外が発生します。

リソースmessage.txtはsrc / main / resourcesにあります。jarを検査して、最上位レベル(application.propertiesと同じレベル)に「message.txt」ファイルが含まれていることを確認しました。

ここにアプリケーションがあります:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application implements CommandLineRunner {

    private static final Logger logger = Logger.getLogger(Application.class);

    @Value("${message.file}")
    private Resource messageResource;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... arg0) throws Exception {
        // both of these work when running as Spring boot app from STS, but
        // fail after mvn package, and then running as java -jar
        testResource(new ClassPathResource("message.txt"));
        testResource(this.messageResource);
    }

    private void testResource(Resource resource) {
        try {
            resource.getFile();
            logger.debug("Found the resource " + resource.getFilename());
        } catch (IOException ex) {
            logger.error(ex.toString());
        }
    }
}

例外:

c:\Users\glyoder\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-proble
m\target>java -jar demo-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.1.5.RELEASE)

2014-09-16 08:46:34.635  INFO 5976 --- [           main] demo.Application
                  : Starting Application on 8W59XV1 with PID 5976 (C:\Users\glyo
der\Documents\workspace-sts-3.5.1.RELEASE\classpath-resource-problem\target\demo
-0.0.1-SNAPSHOT.jar started by glyoder in c:\Users\glyoder\Documents\workspace-s
ts-3.5.1.RELEASE\classpath-resource-problem\target)
2014-09-16 08:46:34.640 DEBUG 5976 --- [           main] demo.Application
                  : Running with Spring Boot v1.1.5.RELEASE, Spring v4.0.6.RELEA
SE
2014-09-16 08:46:34.681  INFO 5976 --- [           main] s.c.a.AnnotationConfigA
pplicationContext : Refreshing org.springframework.context.annotation.Annotation
ConfigApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014];
root of context hierarchy
2014-09-16 08:46:35.196  INFO 5976 --- [           main] o.s.j.e.a.AnnotationMBe
anExporter        : Registering beans for JMX exposure on startup
2014-09-16 08:46:35.210 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.211 ERROR 5976 --- [           main] demo.Application
                  : java.io.FileNotFoundException: class path resource [message.
txt] cannot be resolved to absolute file path because it does not reside in the
file system: jar:file:/C:/Users/glyoder/Documents/workspace-sts-3.5.1.RELEASE/cl
asspath-resource-problem/target/demo-0.0.1-SNAPSHOT.jar!/message.txt
2014-09-16 08:46:35.215  INFO 5976 --- [           main] demo.Application
                  : Started Application in 0.965 seconds (JVM running for 1.435)

2014-09-16 08:46:35.217  INFO 5976 --- [       Thread-2] s.c.a.AnnotationConfigA
pplicationContext : Closing org.springframework.context.annotation.AnnotationCon
figApplicationContext@1c77b086: startup date [Tue Sep 16 08:46:34 EDT 2014]; roo
t of context hierarchy
2014-09-16 08:46:35.218  INFO 5976 --- [       Thread-2] o.s.j.e.a.AnnotationMBe
anExporter        : Unregistering JMX-exposed beans on shutdown

回答:


201

resource.getFile()リソース自体がファイルシステムで利用可能であると想定します。つまり、jarファイル内にネストすることはできません。これが、STSでアプリケーションを実行すると機能するが、アプリケーションをビルドして実行可能jarから実行すると機能しない理由です。getFile()リソースのコンテンツへのアクセスに使用するのではなく、getInputStream()代わりに使用することをお勧めします。これにより、リソースの場所に関係なく、リソースのコンテンツを読み取ることができます。


6
私の場合、(tomcat httpsコネクタのために)キーストアファイルへのパスを指定する必要があります.jksファイルをjar内にラップします。上記の解決策によれば、それは不可能です。それを行うための追加の方法を知っていますか?
Modi、2014年

1
私には非常に似た要件があり、jarの一部としてキーストアを設定できるAPIはありません。@Modi、何か解決策を見つけることができましたか?
Robin Varghese 2015年

キーストアのユースケースを意味しますか?TombootでSpring Bootを使用していますか?
Modi

@RobinVargheseは問題の解決策を見つけましたか?解決すべき同様のユースケースがあります。何か提案があれば感謝します。
horizo​​n7

Tomcatがhttpsを有効にするためにキーストアの場所を必要とする場合classpath:filename、jar内からキーストアファイルを読み取ることができるように使用できます。
horizo​​n7

60

Springフレームワークを使用している場合、への読み取りClassPathResourceは、SpringフレームワークStringを使用して非常に簡単です。FileCopyUtils

String data = "";
ClassPathResource cpr = new ClassPathResource("static/file.txt");
try {
    byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
    data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
    LOG.warn("IOException", e);
}

ファイルを配置する場所に関する制約はありますか?クラスパスのどこにあってもかまいませんか?プロジェクトのルートになることはできますか?
ステファン

クラスパスのどこでもかまいません。
anubhava

45

ファイルを使用したい場合:

ClassPathResource classPathResource = new ClassPathResource("static/something.txt");

InputStream inputStream = classPathResource.getInputStream();
File somethingFile = File.createTempFile("test", ".txt");
try {
    FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
    IOUtils.closeQuietly(inputStream);
}

7

jarとして実行されている春のブートプロジェクトでクラスパスのファイルを読み取る必要がある場合、以下のコードで実装します

Resource resource = new ClassPathResource("data.sql");
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
reader.lines().forEach(System.out::println);

3

クラスパスからファイルを簡単に読み取れるように、Java 8の方法でClassPathResourceReaderクラスを作成しました

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

import org.springframework.core.io.ClassPathResource;

public final class ClassPathResourceReader {

    private final String path;

    private String content;

    public ClassPathResourceReader(String path) {
        this.path = path;
    }

    public String getContent() {
        if (content == null) {
            try {
                ClassPathResource resource = new ClassPathResource(path);
                BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
                content = reader.lines().collect(Collectors.joining("\n"));
                reader.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        return content;
    }
}

利用:

String content = new ClassPathResourceReader("data.sql").getContent();

2

私も、この制限が発生し、問題を克服するために、このライブラリを作成しました:春ブートジャー・リソース それは基本的に透過的に、必要に応じてJARからクラスパスリソースを抽出春ブーツでカスタムResourceLoaderを登録することができます。


2
to get list of data from src/main/resources/data folder --
first of all mention your folder location in properties file as - 
resourceLoader.file.location=data

inside class declare your location. 

@Value("${resourceLoader.file.location}")
    @Setter
    private String location;

    private final ResourceLoader resourceLoader;

public void readallfilesfromresources() {
       Resource[] resources;

        try {
            resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:" + location + "/*.json");
            for (int i = 0; i < resources.length; i++) {
                try {
                InputStream is = resources[i].getInputStream();
                byte[] encoded = IOUtils.toByteArray(is);
                String content = new String(encoded, Charset.forName("UTF-8"));
                }
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
}

1

ジャージーは解凍された瓶である必要があります。

<build>  
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <requiresUnpack>
                    <dependency>
                        <groupId>com.myapp</groupId>
                        <artifactId>rest-api</artifactId>
                    </dependency>
                </requiresUnpack>
            </configuration>
        </plugin>
    </plugins>
</build>  

0
in spring boot :

1) if your file is ouside jar you can use :        

@Autowired
private ResourceLoader resourceLoader;

**.resource(resourceLoader.getResource("file:/path_to_your_file"))**

2) if your file is inside resources of jar you can `enter code here`use :

**.resource(new ClassPathResource("file_name"))**

0

Andyの回答に基づいて、リソース内のディレクトリとサブディレクトリの下にあるすべてのYAMLの入力ストリームを取得するために次を使用しました(渡されたパスがで始まっていないことに注意してください/):

private static Stream<InputStream> getInputStreamsFromClasspath(
        String path,
        PathMatchingResourcePatternResolver resolver
) {
    try {
        return Arrays.stream(resolver.getResources("/" + path + "/**/*.yaml"))
                .filter(Resource::exists)
                .map(resource -> {
                    try {
                        return resource.getInputStream();
                    } catch (IOException e) {
                        return null;
                    }
                })
                .filter(Objects::nonNull);
    } catch (IOException e) {
        logger.error("Failed to get definitions from directory {}", path, e);
        return Stream.of();
    }
}

0

私も同様の状況で立ち往生していますが、厳密には似ていません。resourcesfolder.src / main / resourcesからJSONファイルを読みたかったため、以下のようなコードを記述しました。

ここでは、Spring Boot Applicationのクラスパスからファイルを読み取るさまざまな方法を示します。

@Value( "classpath:test.json")プライベートリソースリソース。

File file = resource.getFile();

@Value("classpath:test.json")

プライベートリソースリソース。

File file = resource.getFile();

今、このコードは、mvn:spring-boot:runを使用して実行すると完全に正常に動作しますが、mavenを使用してアプリケーションをビルドおよびパッケージ化し、単純な実行可能jarとして実行すると、例外が発生します。では、先に進んで解決策を見つけましょう。

InputStreamを使用すると、私の場合に答えが見つかりました:-

@Value("classpath:test.json")
    Resource resourceFile;

private void testResource(Resource resource) {
        try {
            InputStream resourcee = resource.getInputStream();
            String text = null;
            try (final Reader reader = new InputStreamReader(resourcee)) {
                text = CharStreams.toString(reader);
            }
            System.out.println(text);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

SpringはFat Jarの概念で機能するため、Eclipseでの動作やjarとして実行している間は動作が異なるため、実際には困難です。


0

もともとのエラーメッセージについて

ファイルシステムに存在しないため、絶対ファイルパスに解決できません

次のコードは、パスの問題の解決策を見つけるのに役立ちます。

Paths.get("message.txt").toAbsolutePath().toString();

これにより、アプリケーションが欠落しているファイルを予期している場所を特定できます。これは、アプリケーションのメインメソッドで実行できます。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.