java - Read only the first 5 characters and discard rest -


i want read first 5 characters system.in , discard rest eol character if stream contains more (in order start reading next line). here's tried:

private static final int read_count = 5;  public static void main(string[] args) throws ioexception, interruptedexception{     bufferedreader reader = new bufferedreader(new inputstreamreader(system.in));     int readcharacters = 0;     int character;     do{         character = reader.read();         dojob();         if(++readcharacters >= read_count){             discardrest(reader);             break;         }     } while(character != '\n');      system.out.println((char) reader.read()); }  private static void discardrest(bufferedreader reader) throws ioexception {     while(true){         int character = reader.read();         if(character == '\n')             break;     }  }  public static void dojob() throws interruptedexception{     thread.sleep(1000); } 

it works, it's pain. , looks ugly hell. not quite sure if it's reliable. there better way achieve that?

i have made class of own:

public class skiplinebufferedreader extends bufferedreader {      public skiplinebufferedreader(reader in)      {         super(in);     }      public skiplinebufferedreader(reader in, int sz)      {         super(in, sz);     }      //return \n or -1 if eof     public int skipline() throws ioexception     {         int ch;                 {             ch = read();         }         while (ch != -1 && ch != '\n');          return ch;     } } 

that contains logic skip next line reading 1 char @ time.
beware in discardrest if reach eof before eol you'll loop forever.

the use of class above intuitive:

private static final int read_count = 5;   public static void main(string[] args) throws ioexception {     skiplinebufferedreader li          = new skiplinebufferedreader(new inputstreamreader(system.in));      int readcharacters = 0;     int character;          {         character = li.read();          system.out.println("job " + character);          if(++readcharacters >= read_count)         {             li.skipline();              break;         }     } while(character != '\n');      system.out.println((char) li.read()); } 

i don't know if need more specific methods, 1 convert first characters string, bufferedreader has read(char[] cbuf) , read(char[] cbuf, int off, int len) handy deal strings.

beware of dealing string when reading user files, cannot assume there @ least 5 characters, blind substring throws.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -