我有一个带有以下输出的txt文件:
"CN=COUD111255,OU=Workstations,OU=Mis,OU=Accounts,DC=FLHOSP,DC=NET"
我要做的是阅读COUD111255部件并将其分配给java变量。我将ldap分配给sCurrentLine,但是我得到了一个零点异常。任何建议。
try (BufferedReader br = new BufferedReader(new FileReader("resultofbatch.txt")))
{
final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
try {
while ((sCurrentLine = br.readLine()) != null) {
//Write the function you want to do, here.
String[] tokens = PATTERN.split(","); //This will return you a array, containing the string array splitted by what you write inside it.
//should be in your case the split, since they are seperated by ","
}
System.out.println(sCurrentLine);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
});
答案 0 :(得分:0)
您只需逐行读取文件中的数据,并将该行分配给变量str。请参阅以下链接: How to read a large text file line by line using Java?
答案 1 :(得分:0)
要从.txt中读取,请使用BufferedReader。要创建一个,请写:
BufferedReader br = new BufferedReader(new FileReader("testing.txt"));
testing.txt是您正在阅读的txt的名称,必须在您的java文件中。初始化后,您必须继续:
while ((CurrentLine = br.readLine()) != null) {
//Write the function you want to do, here.
String[] tokens = CurrentLine.split(","); //This will return you a array, containing the string array splitted by what you write inside it.
//should be in your case the split, since they are seperated by ","
}
你有令牌数组= [CN = COUD111255,OU =工作站OU = Mis,OU =账户,DC = FLHOSP,DC = NET]。 所以,现在取数组的第0个元素并使用它。你现在得到了CN = COUD111255!离开这里不要给出完整的代码。
希望有所帮助!
答案 2 :(得分:0)
您的代码几乎是正确的。您正在将此字符串写入标准输出 - 用于什么?如果我理解你,你需要的只是这个:
private static final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
public static String solve(String str) {
Matcher matcher = PATTERN.matcher(str);
if (matcher.matches()) {
return matcher.group(1);
} else {
throw new IllegalArgumentException("Wrong string " + str);
}
}
此次电话
solve("CN=COUD111255,OU=Workstations,OU=Mis,OU=Accounts,DC=FLHOSP,DC=NET")
给了我“COUD111255”作为答案。