簡體   English   中英

讀取 Spring boot fat jar 內的文件

[英]Reading file inside Spring boot fat jar

我們有一個 spring boot 應用程序,它有一個遺留的 jar api,我們使用它需要使用 InputFileStream 加載屬性。 我們將遺留 jar 包在我們的 spring boot fat jar 中,屬性文件位於 BOOT-INF/classes 文件夾下。 我可以看到 spring 加載了所有相關的屬性,但是當我將屬性文件名傳遞給遺留 jar 時,它無法讀取屬性文件作為它在 jar 內部並且不在物理路徑下。 在這種情況下,我們如何將屬性文件傳遞給遺留 jar?

請注意,我們無法更改舊 jar。

我最近也遇到了這個問題。 我有一個文件放在資源文件中,我們稱之為path ,但我無法讀取它。 @madoke 給出了使用 FileSystem 的解決方案之一。 這是另一個,這里我們假設我們在一個容器中,如果不是,我們使用 Java 8 特性。

@Component 
@Log4j2
public class DataInitializer implements 
    ApplicationListener<ApplicationReadyEvent> {

private YourRepo yourRepo; // this is your DataSource Repo

@Value(“${path.to.file}”). // the path to file MUST start with a forward slash: /iaka/myfile.csv
private String path;

public DataInitializer(YourRepo yourRepo) {
    this.yourRepo = yourRepo;
}

@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
    try {
        persistInputData();
        log.info("Completed loading data");
    } catch (IOException e) {
        log.error("Error in reading / parsing CSV", e);
    }
}

private void persistInputData() throws IOException {
    log.info("The path to Customers: "+ path);
    Stream<String> lines;
    InputStream inputStream = DataInitializer.class.getClassLoader().getResourceAsStream(path);
    if (inputStream != null) { // this means you are inside a fat-jar / container
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        lines = bufferedReader.lines();
    } else {
        URL resource = this.getClass().getResource(path);
        String path = resource.getPath();
        lines = Files.lines(Paths.get(path));
    }

    List<SnapCsvInput> inputs = lines.map(s -> s.split(","))
                                     .skip(1) //the column names
                                     .map(SnapCsvInput::new)
                                     .collect(Collectors.toList());
    inputs.forEach(i->log.info(i.toString()));
    yourRepo.saveAll(inputs);

}

}

其實你可以,使用FileSystem 您只需要在需要從中獲取文件的文件夾上模擬文件系統。 例如,如果您想獲取src/main/resources下的file.properties ,您可以執行以下操作:

FileSystem fs = FileSystems.newFileSystem(this.getClass().getResource("").toURI(), Collections.emptyMap());
String pathToMyFile = fs.getPath("file.properties").toString();
yourLegacyClassThatNeedsAndAbsoluteFilePath.execute(pathToMyFile)

基本上,你不能,因為屬性“文件”不是一個文件,它是一個 jar 文件中的資源,它被壓縮(它實際上是一個 .zip 文件)。

AFAIK,使這項工作的唯一方法是從 jar 中提取文件,並將其放在您的服務器上的一個眾所周知的位置。 然后在運行時使用 FileInputStream 打開該文件並將其傳遞給遺留方法。

我想從resources文件夾中讀取一個JSON文件。src / main / resources因此在下面編寫了類似這樣的代碼。

Spring Boot Reading Spring Boot中的參考資源不適用於胖子。 在花了很多時間處理這些簡單的事情之后,我發現下面的工作。

如果發胖了,我在Spring Boot中找到了閱讀資源詳細鏈接

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

    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();
        }

根據@moldovean 的解決方案,您只需要調用“getResourceAsStream(path)”並繼續返回的InputStream。 請注意,“路徑”基於 ClassPath。 例如:

InputStream stream = this.getClass().getResourceAsStream("/your-file.csv");

在類路徑的根目錄中,有一個名為“your-file.csv”的文件要讀取。

暫無
暫無

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

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