加载资源文件时出现问

时间:2013-08-12 20:27:17

标签: java file resources apache-commons

我正在开发一个小程序,它应该为我做烦人的复制和粘贴。 所以我编写了一个代码,允许我插入正确的标题,数字等,然后将我的输入复制到正确的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模板)写入文件的任何其他想法?

1 个答案:

答案 0 :(得分:0)

在广告文件中,jarpath来自getCodeSource()将包含

jar:PATH_OF_JAR!PATH_IN_JAR

其中PATH_OF_JAR是

file:/.... .jar

使用Java 7,您可以使用Zip FileSystem进行基于文件的维护。

通常,改变运行代码是一种不好的方法,重新考虑使用生成jar的构建管道。作为 maven 的粉丝,我经常按照这条路径生成资源。