从命令行读取时插入到 ArrayList 的空元素
Empty element inserted into ArrayList when reading from command line
我有代码运行使用以下代码从给定用户的命令行获取用户组列表:
private ArrayList<String> accessGroups = new ArrayList<String>();
public void setAccessGroups(String userName) {
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("/* code to get users */");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
// This code needs some work
while ((line = input.readLine()) != null){
System.out.println("#" + line);
String[] temp;
temp = line.split("\s+");
if(line.contains("GRPNAME-")) {
for(int i = 0; i < temp.length; i++){
accessGroups.add(temp[i]);
}
}
}
// For debugging purposes, to delete
System.out.println(accessGroups);
} catch (IOException e) {
e.printStackTrace();
}
}
获取用户 returns 结果的代码包含以下内容:
#Local Group Memberships *localgroup1 *localgroup2
#Global Group memberships *group1 *group2
# *group3 *group4
# *GRPNAME-1 *GRPNAME-2
该代码旨在提取任何以 GRPNAME- 开头的内容。这工作正常,只是如果我打印 ArrayList
我得到:
[, *GRPNAME-1, *GRPNAME-2]
有对 ""
字符串的引用。有没有一种简单的方法可以改变正则表达式,或者我可以尝试使用另一种解决方案来避免在添加时发生这种情况。
预期输出为:
[*GRPNAME-1, *GRPNAME-2]
编辑:已回答,编辑输出以反映代码中的更改。
最后简单回答,代替:
temp = line.split("\s+");
使用:
temp = line.trim().split("\s+");
而不是此代码段中显示的这种标记化:
line.split("\s+");
使用模式匹配 \S+
并将它们添加到您的 collection。例如:
// Class level
private static final Pattern TOKEN = Pattern.compile("\S+");
// Instance level
{
Matcher tokens = TOKEN.matcher(line);
while (tokens.find())
accessGroups.add(tokens.group());
}
我有代码运行使用以下代码从给定用户的命令行获取用户组列表:
private ArrayList<String> accessGroups = new ArrayList<String>();
public void setAccessGroups(String userName) {
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("/* code to get users */");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
// This code needs some work
while ((line = input.readLine()) != null){
System.out.println("#" + line);
String[] temp;
temp = line.split("\s+");
if(line.contains("GRPNAME-")) {
for(int i = 0; i < temp.length; i++){
accessGroups.add(temp[i]);
}
}
}
// For debugging purposes, to delete
System.out.println(accessGroups);
} catch (IOException e) {
e.printStackTrace();
}
}
获取用户 returns 结果的代码包含以下内容:
#Local Group Memberships *localgroup1 *localgroup2
#Global Group memberships *group1 *group2
# *group3 *group4
# *GRPNAME-1 *GRPNAME-2
该代码旨在提取任何以 GRPNAME- 开头的内容。这工作正常,只是如果我打印 ArrayList
我得到:
[, *GRPNAME-1, *GRPNAME-2]
有对 ""
字符串的引用。有没有一种简单的方法可以改变正则表达式,或者我可以尝试使用另一种解决方案来避免在添加时发生这种情况。
预期输出为:
[*GRPNAME-1, *GRPNAME-2]
编辑:已回答,编辑输出以反映代码中的更改。
最后简单回答,代替:
temp = line.split("\s+");
使用:
temp = line.trim().split("\s+");
而不是此代码段中显示的这种标记化:
line.split("\s+");
使用模式匹配 \S+
并将它们添加到您的 collection。例如:
// Class level
private static final Pattern TOKEN = Pattern.compile("\S+");
// Instance level
{
Matcher tokens = TOKEN.matcher(line);
while (tokens.find())
accessGroups.add(tokens.group());
}