Java实现Grep
grep.java
import java.io.*; public class grep{ public static void main(String [] args) throws IOException{ if(args.length<1){ System.out.println("zu wenige Parameter"); throw new IllegalArgumentException("zu wenig Parameter!"); } boolean reversed =false; String pattern; String sfile =""; try{ if(args[0].equals("-v")){ reversed = true; pattern =args[1]; if(args.length>2){ sfile = args[2]; } }else{ pattern = args[0]; if(args.length==2){ sfile = args[1]; } } }catch(IndexOutOfBoundsException ex){ System.out.println("Irgendwas ist beim verarbeiten der Parameter schiefgegangen: " + ex); return; } if (!(sfile.equals(""))){ File myfile; try{ myfile = new File(sfile); }catch(NullPointerException ex){ System.out.println("uhhps das sollte nicht passieren: " + ex); return; } BufferedReader myreader; try{ myreader = new BufferedReader(new FileReader(myfile)); }catch(FileNotFoundException ex){ System.out.println("File Not Found: " + ex); return; } search(myreader, reversed, pattern); }else{ BufferedReader myreader = new BufferedReader(new InputStreamReader(System.in)); try{ search(myreader, reversed, pattern); }catch(IOException ex){ System.out.println("IO Fehler: " +ex); } } } private static void search(BufferedReader myreader, boolean reversed, String pattern) throws IOException{ //System.out.println("Suche nach: " + pattern); while(myreader.ready()){ String sline = myreader.readLine(); if (reversed){ if(!sline.contains(pattern)){ System.out.println(sline); } }else{ if (sline.contains(pattern)){ System.out.println(sline); } } } } }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/10459.html