簡體   English   中英

為什么我在加載文件時收到 NoSuchFileException 錯誤?

[英]Why do I receive a NoSuchFileException error when loading a file?

Files.readString(Paths.get(ClassPathResource("temp.md").uri)

src > main > resources文件夾中的markdown文本是通過上面的代碼加載的。 在本地環境下,檢查文件位置,加載數據正常,但是在ec2上執行構建的jar時,返回如下錯誤。

我覺得,建的jar的路徑不對,不知道怎么解決,請指教

或者我們可以使用類加載器實例讀取資源。

    ClassLoader classLoader = SpringBootResourcesApplication.class.getClassLoader();
    File file = new File(classLoader.getResource("temp.md").getFile());

當應用程序打包為 JAR 時,從位於類路徑中的文件加載文件的方式不同。
查看這篇 Baeldung 文章以獲取詳細說明。
這將獨立於代碼的打包方式工作:

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import org.springframework.util.ResourceUtils;

import java.nio.file.Files;

@UtilityClass
public class FileTestUtils {

    @SneakyThrows
    public byte[] getFileAsBytes(String fileName) {
        return Files.readAllBytes(ResourceUtils.getFile("classpath:" + fileName).toPath());
    }

    @SneakyThrows
    public String getFileAsString(String fileName) {
        return new String(Files.readAllBytes(ResourceUtils.getFile("classpath:" + fileName).toPath()));
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM