Question

Here is the structure of my maven project:

main and test folders are under src folder, java and resources folders are under main folder, in the resources folder, there is a csv file ready for reading.

src  
  --main  
    |-- java  
    |-- resources  
           |-- test.csv
test  

As far as I know,
InputStream file = ClassLoader.getSystemResourceAsStream("test.csv");
could get the file content in the resources file.

However, in order to read and parse csv file based on supercsv library, I have to use the following code, but InputStream is not acceptable by CsvBeanReader method.

beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);   

So How can I not only getting the file from resource folder based on the maven structure, but also CsvBeanReader could accept the argument passed in.

Était-ce utile?

La solution

Try using InputStreamReader instead of FileReader.

This is possible because the constructor of CsvBeanReader accepts the abstract class Reader:

CsvBeanReader(Reader reader, CsvPreference preferences)
//Constructs a new CsvBeanReader with the supplied Reader and CSV preferences.

You can construct the InputStreamReader using the InputStream you have obtained:

InputStreamReader(InputStream in)
InputStreamReader(InputStream in, Charset cs)
InputStreamReader(InputStream in, CharsetDecoder dec)
InputStreamReader(InputStream in, String charsetName)

Autres conseils

You could wrap the java.io.InputStream with a java.io.InputStreamReader (which extends java.io.Reader) and pass it to the CsvBeanReader class.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top