You can construct an InputStreamReader from that InputStream
new InputStreamReader(myInputStream, encoding)
Where myInputStream is your InputStream and encoding is a String that defines the encoding used by your datasource.
You can call your CSVReader like this:
new CSVReader(new InputStreamReader(myInputStream, encoding));
Answer from oers on Stack OverflowVideos
Use
CSVReader reader = new CSVReader(new InputStreamReader(input));
Edit to answer the comment
The problem is because you don't have any constructor for FileReader as you want. See the FileReader API for details. But since you will have to convert the byte stream to character stream so you will have to use InputStreamReader. For better performance you can wrap it with a BufferedReader also
CSVReader reader = new CSVReader(new InputStreamReader(input, "UTF-8"));
The bridge between binary bytes / InputStream, and unicode text (Reader/String) is the InputStreamReader. Specify the encoding of the bytes / InputStream if the file is not local.
For reading the CSV file, you can use the BufferedReader class:
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("CSV file location"))
);
After that, use StringTokenizer to read each common separated values from the file, ex.:
if(reader.readLine()!=null) {
StringTokenizer tokens = new StringTokenizer(
// this will read first line and separates values by (,) and stores them in tokens.
(String) reader.readLine(), ",");
tokens.nextToken(); // this method will read the tokens values on each call.
}
For example, the CSV file is having record of a employee, like:
ram,101
- The first time, the
tokens.nextToken()call will returnram. - The second time, the
tokens.nextToken()call will return101.
For reading/manipulating csv in Java, you can check out Apache POI Library.
Rather than reinventing the wheel you could have a look at OpenCSV which supports reading and writing of CSV files. Here are examples of reading & writing
The spreadsheet contains names, phone numbers, email addresses, etc. And the program lists everyone's data, and when you click on them it brings up a page with more detailed information, also pulled from the CSV. On that page you can edit the data, and I want to be able to click a "Save Changes" button, then export the data back to its appropriate line in the CSV--or delete the old one, and append the new.
The content of a file is a sequence of bytes. CSV is a text based file format, i.e. the sequence of byte is interpreted as a sequence of characters, where newlines are delimited by special newline characters.
Consequently, if the length of a line increases, the characters of all following lines need to be moved to make room for the new characters. Likewise, to delete a line you must move the later characters to fill the gap. That is, you can not update a line in a csv (at least not when changing its length) without rewriting all following lines in the file. For simplicity, I'd rewrite the entire file.
Since you already have code to write and read the CSV file, adapting it should be straightforward. But before you do that, it might be worth asking yourself if you're using the right tool for the job. If the goal is to keep a list of records, and edit individual records in a form, programs such as Microsoft Access or whatever the Open Office equivalent is called might be a more natural fit. If you UI needs go beyond what these programs provide, using a relational database to keep your data is probably a better fit (more efficient and flexible than a CSV).
The code can be simplified and improved in several ways, and the inner loop can be made tighter. Let me show you how:
private static List<List<String>> readTXTFile(String csvFileName) throws IOException {
String line = null;
BufferedReader stream = null;
List<List<String>> csvData = new ArrayList<List<String>>();
try {
stream = new BufferedReader(new FileReader(csvFileName));
while ((line = stream.readLine()) != null) {
String[] splitted = line.split(",");
List<String> dataLine = new ArrayList<String>(splitted.length);
for (String data : splitted)
dataLine.add(data);
csvData.add(dataLine);
}
} finally {
if (stream != null)
stream.close();
}
return csvData;
}
- A method should throw an exception as specific as possible, here it's better to use
IOExceptioninstead of simplyException - Whenever possible, return interface types instead of concrete classes. Using
Listis preferred to usingVector, this allows you the flexibility to change the implementation of the collection later - Talking about collections:
Vectoris thread-safe andsynchronizedin many of its public methods, that can cause a performance hit. If you don't need that, it's better to useArrayList, it's a drop-in replacement and won't incur in the performance penalty of synchronization. - There's a simpler way to instantiate a
BufferedReader, using aFileReaderinstead of using anInputStreamReaderplus aFileInputStream. Besides,FileReaderwill take care of pesky details regarding character encoding - There's a simpler way to add elements to the last
Listadded tocsvData, as shown in the code - There's a simpler way to iterate through the
String[]returned bysplit(), using an enhanced loop - Don't forget to close your streams! preferably inside a
finallyblock
If you don't need to add more elements to the returned List<List<String>>, you can use the following alternate version. It's faster because it avoids copying the String[] of split elements, but it won't allow adding new elements, as per the contract of asList():
private static List<List<String>> readTXTFile(String csvFileName) throws IOException {
String line = null;
BufferedReader stream = null;
List<List<String>> csvData = new ArrayList<List<String>>();
try {
stream = new BufferedReader(new FileReader(csvFileName));
while ((line = stream.readLine()) != null)
csvData.add(Arrays.asList(line.split(",")));
} finally {
if (stream != null)
stream.close();
}
return csvData;
}
There are frameworks that allow you to read from a CSV file and configure the record structure into one XML configuration file and will parse files for you. You can use:
- FFP - Flat file parsing library http://jffp.sourceforge.net/
- BeanIO: http://www.beanio.org/
- Fixedformat4j