我想阅读/ 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");
}
}
Run Code Online (Sandbox Code Playgroud)
我注意到两个问题:
不使用root帐户信息读取文件的第一行.我这样开始:
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
Run Code Online (Sandbox Code Playgroud)
我如何修改代码以使用Java 8 NIO?我想首先检查文件的现有内容,然后继续阅读内容.
问题是第一个readLine()是在处理字符串的循环之外,你应该删除它:
str = in.readLine();
Run Code Online (Sandbox Code Playgroud)
...因为在下一行(带有的那一行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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
816 次 |
| 最近记录: |