导出jar时不包括文本和图像文件

X和Y

我创建了一个项目,该项目在执行时会使用图像文件以及文本文件。在将项目导出到可运行的jar之前,文本文件和图像文件都位于我的项目文件夹中,但是当我从命令行运行jar时,由于程序键入要从文本文件读取而导致filenotfound异常。我解压缩了罐子以进行仔细检查,但图像和文本文件不存在。

package application;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import javafx.collections.FXCollections;

public class Data {
    private static Data instance=new Data();
    private Map<String,String> saveEntries = new HashMap<>();
    private static String fileName = "ResponseData";

public static Data getInstance() {
    return instance;
}

public void exitSave() throws IOException {
    Path path = Paths.get("ResponseData");
    Iterator<Map.Entry<String, String>> iter = saveEntries.entrySet().iterator();
    BufferedWriter bw = Files.newBufferedWriter(path);
    try {
        while(iter.hasNext()) {
            Map.Entry<String, String> entry = iter.next();
            bw.write(String.format("%s\t%s", entry.getKey(),entry.getValue()));
            bw.newLine();
        }
    } catch (IOException e) {
        new FileNotFoundException("Error when saving data");
    }finally {
        if(bw!=null)
            bw.close();
    }
}



public void updatedSaveEntry(String input, String response) {
    saveEntries.put(input, response);
}

public Map<String,String> getSaveEntries(){
    return this.saveEntries;
}

public void setEntry(Map<String,String> map) {
    Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
    while(iter.hasNext()) {
        Map.Entry<String, String> entry = iter.next();
        saveEntries.put(entry.getKey(), entry.getValue());
    }
}


public void loadEntries() throws IOException{
    saveEntries = FXCollections.observableHashMap();
    Path path = Paths.get(fileName);
    BufferedReader br = Files.newBufferedReader(path);
    String line;
    try {
        while((line=br.readLine())!=null&&!line.trim().isEmpty()) {
            String[] parts = line.split("\t");
            saveEntries.put(parts[0], parts[1]);
        }
    }finally {
        if(br!=null) {
            br.close();
        }
    }

}

}

Eclipse Runnable Jar导出

项目文件夹

SDJ

如果您正在读取和写入文件,则不如另一个答案中所述在应用程序jar中定位此文件:您应该将数据持久保存在外部位置。

但是,通常将只读资源文件(例如图像)保存在jar中。如果要对图像以及其他资源保留此方法,则面临两个问题:

  1. 使用该Export Runnable Jar功能使Eclipse将文件包含在jar中

  2. 在罐子里找到文件

包括文件

最简单的方法可能只是将文件放在源文件夹中。在您的项目中,执行New -> Source Folder,为其命名(例如,“资源”),然后将文件移到该位置。通常,如果您重新运行导出,则文件应位于jar中。

查找文件

jar中的文件的访问方式不同。请参阅从jar中读取资源文件的可接受答案请注意,您无需在路径中包含资源文件夹的名称,因为此文件将放置在jar的根目录中(您可以通过解压缩来验证它)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章