java - Cannot read first line of a file -


i want read content of /etc/passwd file , data:

public void getlinuxusers()     {         try         {             // !!! firstl line of file not read             bufferedreader in = new bufferedreader(new filereader("/etc/passwd"));             string str;             str = in.readline();             while ((str = in.readline()) != null)             {                 string[] ar = str.split(":");                 string username = ar[0];                 string userid = ar[2];                 string groupid = ar[3];                 string usercomment = ar[4];                 string homedir = ar[5];                  system.out.println("usrname " + username +                          " user id " + userid);             }             in.close();         }         catch (ioexception e)         {             system.out.println("file read error");         }     } 

i noticed 2 problems:

first line of file not read root account information. starts way:

root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin 

and how can modify code use java 8 nio? want check first existing of file , proceed reading content.

the problem first readline() outside loop string being processed, should delete this:

str = in.readline(); 

… because in next line (the 1 while) you're reassigning str variable, that's why first line lost: loop's body starts processing second line. finally, use java nio, this:

if (new file("/etc/passwd").exists()) {     path path = paths.get("/etc/passwd");     list<string> lines = files.readalllines(path, charset.defaultcharset());     (string line : lines) {         // loop body, same yours     } } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -