LapisSea

Untitled

Feb 8th, 2020
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 KB | None | 0 0
  1. static class ColumnView{
  2.         public final int    column;
  3.         public final String data;
  4.        
  5.         ColumnView(int column, String data){
  6.             this.column=column;
  7.             this.data=data;
  8.         }
  9.        
  10.         public <T> T parseStr(Function<String, T> parser){
  11.             return parse(c->parser.apply(c.data));
  12.         }
  13.        
  14.         public <T> T parse(Function<ColumnView, T> parser){
  15.             return parser.apply(this);
  16.         }
  17.     }
  18.    
  19.     public static Stream<ColumnView> csvReader(File file) throws FileNotFoundException{
  20.         return csvReader(new FileInputStream(file));
  21.     }
  22.    
  23.     public static Stream<ColumnView> csvReader(InputStream file){
  24.         Reader        charView   =new InputStreamReader(file instanceof BufferedInputStream?file:new BufferedInputStream(file));
  25.         StringBuilder valueBuffer=new StringBuilder();
  26.         int[]         column     ={0};
  27.         return Stream.generate(()->{
  28.             valueBuffer.setLength(0);
  29.             int     ch;
  30.             boolean eof=true;
  31.            
  32.             try{
  33.                 while((ch=charView.read())!=-1){
  34.                     eof=false;
  35.                     if(ch=='\r') continue;
  36.                     boolean newLine=ch=='\n';
  37.                     if(newLine||ch==','){
  38.                         ColumnView c=new ColumnView(column[0], valueBuffer.toString());
  39.                         if(newLine) column[0]=0;
  40.                         else column[0]++;
  41.                         return c;
  42.                     }
  43.                     valueBuffer.append((char)ch);
  44.                 }
  45.                 if(eof) return null;
  46.                 return new ColumnView(column[0], valueBuffer.toString());
  47.             }catch(IOException e){
  48. //              throw UtilL.uncheckedThrow(e);
  49.                 throw new RuntimeException(e);//replace this with uncheckedThrow if you have it
  50.             }
  51.         }).takeWhile(Objects::nonNull).onClose(()->{
  52.             try{
  53.                 file.close();
  54.             }catch(IOException ignored){}
  55.         });
  56.     }
Add Comment
Please, Sign In to add comment