If you want to read the CSV files from the jar, then they must be included in the jar. Check using jar tvf your.jar
or a zip utility. If reading files from the jar, use InputStreamReader
with getResourceAsStream
.
If you want to read the CSV files from the file system, then you need to have them on the file system, not in the jar (or extract them from the jar before running...). If reading files from file system, use FileReader
with file system filename.
Here is a demonstration...
Two source files - one reading from jar, one reading from filesystem:
$ cat ReadFile.java
import java.io.*;
public class ReadFile {
public static void main(String[] args) throws IOException {
String csvFile = args[0];
BufferedReader reader = new BufferedReader(new FileReader(csvFile));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
$ cat ReadResource.java
import java.io.*;
public class ReadResource {
public static void main(String[] args) throws IOException {
String csvFile = args[0];
BufferedReader reader = new BufferedReader(new InputStreamReader(ReadResource.class.getResourceAsStream(csvFile)));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
The content of the jar - CSV file at _input_/my.csv
:
$ jar tvf readtest.jar
0 Mon Nov 17 12:58:04 GMT 2014 META-INF/
71 Mon Nov 17 12:58:04 GMT 2014 META-INF/MANIFEST.MF
697 Mon Nov 17 12:52:30 GMT 2014 ReadFile.class
842 Mon Nov 17 12:52:30 GMT 2014 ReadResource.class
0 Mon Nov 17 12:47:38 GMT 2014 _input_/
16 Mon Nov 17 12:47:20 GMT 2014 _input_/my.csv
The content of the file system - CSV file at input/my.csv
:
$ mv _input_/ input
$ find .
.
./input
./input/my.csv
./ReadFile.class
./ReadFile.java
./ReadResource.class
./ReadResource.java
./readtest.jar
Using ReadFile, you can read from file system, but not from jar:
$ java -cp readtest.jar ReadFile input/my.csv
foo,bar
bar,foo
$ java -cp readtest.jar ReadFile _input_/my.csv
Exception in thread "main" java.io.FileNotFoundException: _input_\my.csv (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at java.io.FileReader.<init>(FileReader.java:41)
at ReadFile.main(ReadFile.java:5)
Using ReadResource, you can read from jar, but not from file system:
$ java -cp readtest.jar ReadResource input/my.csv
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:61)
at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
at ReadResource.main(ReadResource.java:5)
$ java -cp readtest.jar ReadResource _input_/my.csv
foo,bar
bar,foo