我想读取/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
}
}
关于java - 无法读取文件的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25372761/