给Java项目中的文件提供固定路径(Netbeans)

时间:2013-05-13 17:43:12

标签: java jasper-reports

我有一个生成jasper报告的Java项目,我做的是我给出一个文件路径(报告)并运行我的项目它运行正常,但是当我必须将JAR文件提供给我的朋友时,它总是需要该文件要放在那个特定的文件夹中,根据我的代码获取文件路径然后必须将文件放在那里,我的代码在下面给出一些想法

public void generateReport(String dateStart, String dateEnd) {
    InputStream stream = null;
    Connection connection = null;
    Class.forName("com.mysql.jdbc.Driver");
    connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/app", "root", "");
    stream = new FileInputStream(new File("").getAbsolutePath() + "/reports/logReport.jrxml");
    JasperDesign jasperDesign = JRXmlLoader.load(stream);
    jasperReport = JasperCompileManager.compileReport(jasperDesign);
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, connection);

    //frame.getContentPane().add(dateSetter, BorderLayout.PAGE_START);
    frame.getContentPane().add(new JRViewer300(jasperPrint), BorderLayout.CENTER);
    frame.setResizable(false);
    frame.setSize(900, 600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    isVisible = true;
    connection.close();
    stream.close();
    }

在代码中,它从路径中获取文件

  

/reports/logReport.jrxml

但是当我将JAR文件放在其他地方并运行它时,它会给出错误

  

C:\ Desktop \ reports \ logReport.jrxml找不到指定的路径。

我知道这是由于代码部分new File("").getAbsolutePath(),但我需要知道如何使它始终从项目中获取文件路径!所以我并不总是把那个特定的文件放在那里!

2 个答案:

答案 0 :(得分:2)

如果你想让它成为同一目录的绝对路径,你只需指定整个路径。

stream = new FileInputStream(new File("C:/path/to/my/reports/logReport.jrxml"));

如果你想要它相对于运行jar的目录。

stream = new FileInputStream(new File("path/to/my/reports/logReport.jrxml"));

如果您希望从Jar本身加载文件,则需要采用不同的方式。

stream = this.getClass().getResourceAsStream.("/path/to/my/reports/logReport.jrxml");

答案 1 :(得分:0)

最好从指定位置读取文件

以下是link从指定位置读取文件。

但是如果在服务器上运行相同的代码,则必须指定相对于运行服务器的根目录的路径

 String location = "/opt/reports/";
 String filename = "logReport.jrxml";

 File file = new File(location + filename);