br = new BufferedReader(new FileReader(file));
while ((finalLine = br.readLine()) != null) {
String[] reader = finalLine.split(",");
String foundWord = "dod";
for (String word : reader) {
if (word.equals(foundWord)) {
String NAME = reader[0];
String PASSWORD = reader[1];
String CONTACT_NO = reader[2];
String EMAIL_ADDRESS = reader[3];
我目前正在使用BufferedReader来读取文本文件中的所有行,如果找到“dod”如何在同一行中获取其余信息1.请帮忙。
这些行将
(line 1) dod, 12345, 00112949, test@testacc.com
(line 2) abc, 22222, 0004993, aaa@aaaac.com
在文本文件中,如果找到dod,从上面的代码中,我想要提取第1行数据并保存在变量中。
答案 0 :(得分:0)
如果发现“dod”如何在同一行中获取其余信息
你已经拥有它,在finalLine
变量中。
答案 1 :(得分:-1)
请尝试以下代码:
public static void main(String[] args) {
BufferedReader reader = null;
String line;
String name,pwd,contactNo,email;
try {
reader = new BufferedReader(new FileReader("src/files/temp2.txt"));
String foundWord = "dod";
while ((line = reader.readLine()) != null) {
String[] words = line.split(",");
for (String word : words) {
if (word.equals(foundWord)) {
name = words[0];
pwd = words[1];
contactNo = words[2];
email = words[3];
System.out.println("Details: " +name + "-" + pwd + "-" + contactNo + "-" + email);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
reader.close()
}
}
输出将是:
Details: dod-12345-00112949-test@testacc.com
。如果您愿意,可以将该信息存储在对象中。
答案 2 :(得分:-1)
看看这个:
public class A {
public static void main(String[] args) throws FileNotFoundException {
boolean found = false;
Scanner line = new Scanner(new File("E:/temp.txt"));
String foundWord = "dod";
while (line.hasNextLine()) {
String[] reader = line.nextLine().split(",");
for (String word : reader) {
if (word.equals(foundWord)) {
found = true;
String NAME = reader[0];
String PASSWORD = reader[1];
String CONTACT_NO = reader[2];
String EMAIL_ADDRESS = reader[3];
System.out.println(NAME + "\t" + PASSWORD + "\t"
+ CONTACT_NO + "\t" + EMAIL_ADDRESS);
}
}
}
if (!found) {
System.out.println(foundWord + " not found");
}
}
}
添加如果找不到条件
输出:
dod 12345 00112949 test@testacc.com