我想读取/ etc / passwd文件的内容并获取一些数据:
public void getLinuxUsers()
{
try
{
// !!! firstl line of the file is 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");
}
}
我注意到两个问题:
该文件的第一行未读取根帐户信息。我以这种方式开始:
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
以及如何修改代码以使用Java 8 NIO?我想先检查文件是否存在,然后再继续阅读内容。
问题是,第一个readLine()
是外部的,其中正在处理字符串的循环,你应该删除这个:
str = in.readLine();
…因为在下一行(带有的行while
)中,您正在重新分配str
变量,所以这就是第一行丢失的原因:循环的主体从第二行开始处理。最后,要使用Java nio
,请执行以下操作:
if (new File("/etc/passwd").exists()) {
Path path = Paths.get("/etc/passwd");
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for (String line : lines) {
// loop body, same as yours
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句