我有一个大的文本文件,我想用分隔符将其分隔成不同的字符串!-(每个字符串是多行)。
然后我想丢弃所有其他不包含的字符串:
=========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========
到目前为止,我已经得到了这个,它没有输出任何东西(它符合要求,但没有输出到控制台)。我是编程新手,在研究了一段时间后,我没有取得太大进展,所以任何建议或指针都将不胜感激,谢谢!
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:/Users/Anton/Pictures/1 x geotransform0.5m shading.txt");
Scanner scan = new Scanner(file);
while(scan.hasNextLine()){
StringTokenizer st = new StringTokenizer(scan.nextLine(),"!-");
if(st.equals(" =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========")) {
System.out.print(st);
}
}
scan.close();
}
}
您应该考虑将java文档页面读取到StringTokenizer
:http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
您的代码中存在两个不同的问题:
- 因为所需的字符串是一个文件中的多行,所以您必须首先将它们相加(到
String
中),然后通过StringTokenizer
进行处理以再次分离 - 您必须将
StringTokenizer.nextToken()
与您的支票String
进行比较,而不是将整个StringTokenizer
进行比较。StringTokenizer.nextToken()
然后为您提供通过!-
分隔的下一个字符串
以下代码应该有效:
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:/Users/Anton/Pictures/1 x geotransform0.5m shading.txt");
Scanner scan = new Scanner(file);
//Scanning
//first scan the whole file into a string (because a sting can have more than one line)
String temp = "";
while(scan.hasNextLine()){
temp = scan.nextLine();
}
//now add the string to tokeinzer
StringTokenizer st = new StringTokenizer(temp,"!-");
//now give output
while(st.hasMoreTokens()){
String temp2 = st.nextToken();
if(temp2.equals(" =========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========")) {
System.out.print(temp2);
}
}
scan.close();
}
}
}
删除if条件并添加以下while条件
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
因为stringtokenizer根据标记来分割文本。所以你的if永远不会变成真的。
试试这个。。。。。。。。。。。
while(scan.hasNextLine()){
StringTokenizer st = new StringTokenizer(scan.nextLine(),"!-");
while(st.hasMoreTokens()){
String stt = st.nextElement().toString();
if(stt.equals("=========== ALL OBJECTS IN CLASS: FENESTRATIONSURFACE:DETAILED ===========")) {
System.out.print(stt);
}
}
}
您正在将字符串与字符串生成器对象进行比较,而不是值。。。。