gpt4 book ai didi

java - 导出 jar 时不包含文本和图像文件

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:30 25 4
gpt4 key购买 nike

我创建了一个项目,在执行时使用图像文件和文本文件。在将项目导出到可运行的 jar 之前,文本和图像文件都位于我的项目文件夹中,但是当我从命令行运行 jar 时,我收到了一个 filenotfound 异常,该异常是由程序键入从文本文件中读取而引起的。我解压 jar 并仔细检查,图像和文本文件不在那里。

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 Export

Project Folder

最佳答案

如果您同时写入一个文件,那么在应用程序 jar 中定位该文件是不合适的,正如另一个答案中提到的:您应该将数据保存在外部位置。

但是,通常会将只读资源文件(例如图像)保留在 jar 中。如果您想对图像和可能的其他资源保留这种方法,您将面临两个问题:

  1. 使用导出可运行 Jar 功能让 Eclipse 将文件包含在 jar 中。

  2. 在 jar 中查找文件

包含文件

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

查找文件

jar 中的文件的访问方式不同。请参阅 Reading a resource file from within jar 已接受的答案。请注意,您不需要在路径中包含资源文件夹的名称,因为该文件将放置在 jar 的根目录中(您可以通过解压它来验证这一点)。

关于java - 导出 jar 时不包含文本和图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56912066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com