Java 尝试从txt文件检索信息时出现问题
我在申请表中遇到了一个问题。我有一个文本文件,其中包含一段代码,我需要检索这些代码才能应用到一个字符串变量中。问题是这样做的最佳方式是什么?我在下面运行了这些示例,但它们在逻辑上不正确/不完整。看一看:Java 尝试从txt文件检索信息时出现问题,java,string,text,java.util.scanner,bufferedreader,Java,String,Text,Java.util.scanner,Bufferedreader,我在申请表中遇到了一个问题。我有一个文本文件,其中包含一段代码,我需要检索这些代码才能应用到一个字符串变量中。问题是这样做的最佳方式是什么?我在下面运行了这些示例,但它们在逻辑上不正确/不完整。看一看: 通读行: BufferedReader bfr = new BufferedReader(new FileReader(Node)); String line = null; try { while( (line = bfr.readLine()) != null ){
BufferedReader bfr = new BufferedReader(new FileReader(Node));
String line = null;
try {
while( (line = bfr.readLine()) != null ){
line.contentEquals("d.href");
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader bfr = new BufferedReader(new FileReader(Node));
int i = 0;
try {
while ((i = bfr.read()) != -1) {
char ch = (char) i;
System.out.println(Character.toString(ch));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
BufferedReader bfr = new BufferedReader(new FileReader(Node));
BufferedReader bfr = new BufferedReader(new FileReader(Node));
int wordCount = 0, totalcount = 0;
Scanner s = new Scanner(googleNode);
while (s.hasNext()) {
totalcount++;
if (s.next().contains("(?=d.href).*?(}=?)")) wordCount++;
}
System.out.println(wordCount+" "+totalcount);
d.href
With包含代码段的开头。使用(2.)时,我无法思考或找到一种方法将
d.href
存储为字符串并检索其余信息。使用(3.)我可以正确地找到
d.href
,但我无法检索txt的片段
有人能帮我吗?您可以使用如下正则表达式:
Pattern pattern = Pattern.compile("^\\s*d\\.href([^=]*)=(.*)$");
// Groups: 1-----1 2--2
// Possibly spaces, "d.href", any characters not '=', the '=', any chars.
....
Matcher m = pattern.matcher(line);
if (m.matches()) {
String dHrefSuffix = m.group(1);
String value = m.group(2);
System.out.println(value);
break;
}
BufferedReader就可以了。作为我问题的答案,我使用扫描仪逐字读取文本文件
.contains(“window.maybeRedirectForGBV”)
返回一个布尔值,hasNext()
返回一个字符串。然后,我提前一个字停止了对文本文件的代码拉伸查询,并再次向前移动,将下一个字的值存储在一个字符串变量上。从这一点上讲,您只需要按照您想要的方式处理字符串。希望这有帮助
String stringSplit = null;
Scanner s = new Scanner(Node);
while (s.hasNext()) {
if (s.next().contains("window.maybeRedirectForGBV")){
stringSplit = s.next();
break;
}
}
Scanner
可能出现问题,因为next
将检索由空格分隔的文本。您可能需要设置分隔符(使用setDelimiter
,或者我认为这就是它的名称),或者使用nextLine
而不是next
。很难准确理解您要做的事情。你能给出示例输入和输出吗?据我所知,代码是有道理的,但我没有成功,控制台上没有出现任何问题,甚至我已经改为Pattern=Pattern.compile(“d.href”);或者Pattern=Pattern.compile(“a”)<代码>匹配对整行进行匹配<代码>而(m.find())是另一种选择。此代码应该使用*\\b
(任何字符,单词边界)而不是\\s*
(空格)。感谢您的帮助,尽管我找到了另一种方法来解决我的问题,请检查我的答案您的解决方案应该更快,因为模式匹配速度非常慢。看到有人解决问题总是很高兴。附言:接受你自己的答案,将问题标记为已解决。我等待2天的延迟来完成此操作;))谢谢你的支持!!