在可执行jar中使用文件运行时问题

时间:2019-04-07 12:26:50

标签: java file-io jar runtime executable

我有一个有效的代码(至少在eclipse中),其中使用了一些文件:我有一个.dot文件,我在其中写入了一些文本,因此可以阅读以创建图形。然后,将图形保存为.png图像,并显示在框架上。

我的问题是:在可执行.jar文件中,我无法访问这些文件,而且-如果我知道正确-我什至无法更改em运行时。因此,我尝试使用Streams。我可以像这样访问.dot文件:

$InputStream fileStream = this.getClass().getResourceAsStream("/graf.dot");$

但是我不知道该如何写。我找到了 OutputStreamWriter ,但它还需要一个路径,就像访问InputStream一样,我无法访问。我也很难从文件中读取文本并创建.png文件...你能帮我么?甚至可以在运行时使用这些文件吗?

访问框架的背景图像时遇到相同的问题,但是找到了解决方法:

$URL bgPath = this.getClass().getResource("/background.jpg");
panel = new JLabel(new ImageIcon(bgPath));$

所以我真的希望对我使用的文件存在一些类似的解决方案。

private void createGraph() throws IOException { 
    /* Creating the graph into "graf.dot" file.
     * The format is in DOT language.
     */
    String fileName = "src/main/resources/graf.dot";
    InputStream fileStream = this.getClass().getResourceAsStream("/graf.dot");
    BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));
    /* Here I write the content into *graph_string**/
    br.close();
    try {
        FileOutputStream outputStream = new FileOutputStream(fileName);
        OutputStreamWriter writer = new OutputStreamWriter(outputStream);
        //FileWriter writer = new FileWriter(fileName);
        writer.write(graph_string);
        writer.close();
    }catch (IOException e) {
        System.out.println("Error writing into file");
    }finally {
        drawGraph();            
    }
}

private void drawGraph() throws IOException {   
    /*
     * Reading the graph from file for visualization
     */
    String fileName = "src/main/resources/graf.dot";
    InputStream fileStream = this.getClass().getResourceAsStream("/graf.dot");
    BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));      
    File file = new File("src/main/resources/graf.dot");
    String str="";
    try {
       str = FileUtils.readFileToString(file, "UTF-8");
    } catch (IOException e) {
        System.out.println("Errorrr reading from file.");
    }
    MutableGraph g = Parser.read(str);  
    Graphviz.fromGraph(g).render(
            Format.PNG).toFile(new File("src/main/resources/graph.png"));
    BufferedImage background = ImageIO.read(new File("src/main/resources/graph.png"));
    panel = new JLabel(new ImageIcon(background));          
...
}

0 个答案:

没有答案