我正在开发一个小程序,它应该为我完成烦人的复制和粘贴工作。 所以我写了一个代码,允许我插入正确的标题、数字等,然后将我的输入复制到 4 个不同文件中的正确位置。 我准备了一些文件(.xml 和 .html)以便编辑更容易。 我使用关键字,然后 .replaceAll("", "");
我的计划是将准备好的文件保留为资源,这样我就可以将我的 .jar 拖到我计算机上的任何位置,让程序从我的资源中生成新文件,并编辑与我的 .jar 在同一目录中的文件.
好吧,每当我通过 eclipse 启动我的应用程序时,一切都很好。 该程序使用我的模板根据我的输入创建新文件,并编辑我选择编辑的现有文件。 但是,当我将所有内容导出到 .jar 中时,程序会在某个点停止,不会出现错误或类似情况。
jarpath = getClass().getProtectionDomain().getCodeSource()
.getLocation().getPath().substring(1);
//substring removes a /
jarpathparent = jarpath.replace("alpha.jar", "");
// replacing with "" to get the only the directory where the .jar is.
public void generate(String s) throws IOException {
String path = "", content = "";
File file = null, outputfile = null;
switch (s) {
case "index":
Dialog.info("", "1");
path = getClass().getResource("index.html").toString()
.replace("file:/", "");
Dialog.info("", "2");
file = new File(path);
Dialog.info("", "3");
outputfile = new File(jarpathparent + "/index.html");
Dialog.info("", "4");
content = FileUtils.readFileToString(file);
Dialog.info("", "5");
content = content.replaceAll("XforTitle", title);
Dialog.info("", "6");
FileUtils.writeStringToFile(outputfile, content);
Dialog.info("", "7");
break;
case "index2":
.
.
.
我使用了我创建的一个小对话框类来发现程序停止的位置。 第四个对话框是最后一个弹出的,所以问题似乎是
content = FileUtils.readFileToString(file);
我不知道到底出了什么问题,但也许是因为我使用了 apache-commons-io (FileUtils) 或类似的东西?
也许还有一个包含整个代码的 pastebin 链接: http://pastebin.com/Px7SygYu (图像标签和 .wav 仅供娱乐。)
___________编辑____________< em>____
好的,我现在可以加载资源内容了
通过使用
InputStream input = getClass().getResourceAsStream("/classpath/to/my/file");
和来自
的代码片段http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/
所以我现在将文件的内容作为一个字符串,并想将它写入一个新文件(在我放置 .jar 的目录中)
InputStream input = getClass().getResourceAsStream("index.html");
content = getStringFromInputStream(input);
Dialog.info("", "2");
outputfile = new File(jarpathparent + "index.html");
Dialog.info("", "3");
content = content.replaceAll("XforTitle", title);
Dialog.info("", "4");
Dialog.info("", outputfile.getPath());
try {
FileUtils.writeStringToFile(outputfile, content);
} catch (Exception e) {
Dialog.vielText("", e.toString());
}
Dialog.info("", "5");
所以它现在在 FileUtils.writeStringToFile(...) 崩溃了; 但我不会删除对话框,但应在我的 try catch 中捕获异常。 我检查了输出路径,正如您在代码中看到的那样,它似乎没问题。 关于如何修复甚至如何将我的字符串(包含 .html 模板)写入文件的任何其他想法?
最佳答案
在一个 jar 中,jarpath
通过 getCodeSource()
将包含
jar:PATH_OF_JAR!PATH_IN_JAR
PATH_OF_JAR 在哪里
file:/.... .jar
对于 Java 7,您可以使用 Zip FileSystem进行基于文件的维护。
一般来说,更改正在运行的代码是一种糟糕的方法,请重新考虑使用生成 jar 的构建管道。作为 maven 的粉丝,我经常遵循这条生成资源的道路。
关于java - 加载资源文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18196084/