Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static class ColumnView{
- public final int column;
- public final String data;
- ColumnView(int column, String data){
- this.column=column;
- this.data=data;
- }
- public <T> T parseStr(Function<String, T> parser){
- return parse(c->parser.apply(c.data));
- }
- public <T> T parse(Function<ColumnView, T> parser){
- return parser.apply(this);
- }
- }
- public static Stream<ColumnView> csvReader(File file) throws FileNotFoundException{
- return csvReader(new FileInputStream(file));
- }
- public static Stream<ColumnView> csvReader(InputStream file){
- Reader charView =new InputStreamReader(file instanceof BufferedInputStream?file:new BufferedInputStream(file));
- StringBuilder valueBuffer=new StringBuilder();
- int[] column ={0};
- return Stream.generate(()->{
- valueBuffer.setLength(0);
- int ch;
- boolean eof=true;
- try{
- while((ch=charView.read())!=-1){
- eof=false;
- if(ch=='\r') continue;
- boolean newLine=ch=='\n';
- if(newLine||ch==','){
- ColumnView c=new ColumnView(column[0], valueBuffer.toString());
- if(newLine) column[0]=0;
- else column[0]++;
- return c;
- }
- valueBuffer.append((char)ch);
- }
- if(eof) return null;
- return new ColumnView(column[0], valueBuffer.toString());
- }catch(IOException e){
- // throw UtilL.uncheckedThrow(e);
- throw new RuntimeException(e);//replace this with uncheckedThrow if you have it
- }
- }).takeWhile(Objects::nonNull).onClose(()->{
- try{
- file.close();
- }catch(IOException ignored){}
- });
- }
Add Comment
Please, Sign In to add comment