Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.FileNotFoundException while running java app from jar file

Hi i am running java app from jar file. like following java -cp test.jar com.test.TestMain . in the java app i am reading csv file. which is throwing below exception.

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.

code causes to exception is

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

thanks.

like image 515
Harinath Avatar asked Oct 16 '25 15:10

Harinath


1 Answers

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

Would suggest using

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

and

getResourceAsStream("/us_postal_codes.csv") // if its inside a jar
like image 77
Naman Avatar answered Oct 18 '25 06:10

Naman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!