从jar文件运行java app时出现java.io.FileNotFoundException

时间:2016-05-17 07:42:43

标签: java filenotfoundexception

您好我正在从jar文件运行java app。喜欢关注java.io.FileNotFoundException: file:\C:\Users\harinath.BBI0\Desktop\test.jar!\us_postal_codes.csv (The filename, directory name, or volume label syntax is incorrect) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:146) at java.util.Scanner.<init>(Scanner.java:656) at com.test.TestMain.run(TestMain.java:63) at com.test.TestMain.main(TestMain.java:43) *csv file is located in src/main/resources folder. 。在java应用程序中我正在阅读csv文件。这是抛出异常。

public static void main(String[] args) throws Exception {
    TestMain trainerScraper = new TestMain();
    trainerScraper.run();
}

private void run() throws JsonParseException, JsonMappingException, IOException{
    String line = "";
    String cvsSplitBy = ",";

    //Get file from resources folder
    ClassLoader classLoader = getClass().getClassLoader();
    System.out.println(csvFile);
    URL url = classLoader.getResource("us_postal_codes.csv");
    String fileName = url.getFile();
    File file = new File(fileName);

    try (Scanner scanner = new Scanner(file)) {
        line = scanner.nextLine();          //header
        while ((scanner.hasNextLine())) {

代码导致异常

Select 
 l.id AS "load.id", 
 l.brass_id AS "load.brass_id", 
 b.id AS "brass.id", 
 b.mfg_id AS "brass.mfg_id",
 m.id AS "brass_mfg.id",
 m.`name` AS "brass_mfg.name"
FROM `load` as l
LEFT JOIN brass as b ON l.brass_id = b.id
LEFT JOIN brass_mfg as m ON b.mfg_id = m.id

感谢。

3 个答案:

答案 0 :(得分:3)

  

test.jar!\ us_postal_codes.csv(文件名,目录名或卷)   标签语法不正确)

建议使用

System.getProperty("user.dir") // to get the current directory, if the resource is in the project folder

getResourceAsStream("/us_postal_codes.csv") // if its inside a jar

答案 1 :(得分:2)

根据下面的堆栈跟踪,我们可以看到扫描程序找不到该文件:

at java.util.Scanner.<init>(Scanner.java:656)
at com.test.TestMain.run(TestMain.java:63)

顺便问一下,文件在哪里?如果它在jar中,那么您可以使用TestMain.class.getResourceAsStream() - Scanner也有一个InputStream构造函数:

InputStream iStream = TestMain.class.getResourceAsStream("/us_postal_codes.csv"); // this supposes the csv is in the root of the jar file
try (Scanner scanner = new Scanner(iStream)) {
    //...
}
//...

答案 2 :(得分:1)

您应该使用getResourceAsStream。这是一个例子:

public void test3Columns() throws IOException
{
  InputStream is = getClass().getResourceAsStream("3Columns.csv");
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr);
  String line;
  while ((line = br.readLine()) != null) 
  {
    CSVLineTokenizer tok = new CSVLineTokenizer(line);
    assertEquals("Should be three columns in each row",3,tok.countTokens());
  }
  br.close();
  isr.close();
  is.close();
}

ClassLoader.getResource方法不用于搜索.jar档案中的文件。