+-
从jar文件运行java app时出现java.io.FileNotFoundException
嗨我从jar文件运行 java应用程序.比如以下 java -cp test.jar com.test.TestMain.在java应用程序中我正在阅读csv文件.这是抛出异常.

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.

代码导致异常的是

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())) {

谢谢.

最佳答案

test.jar!\us_postal_codes.csv (The filename, directory name, or volume
label syntax is incorrect)

建议使用

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
点击查看更多相关文章

转载注明原文:从jar文件运行java app时出现java.io.FileNotFoundException - 乐贴网