我有一个Java程序,它使用inputStream从输入文件中读取,并使用outputStream写入输出文件。该文件的注释行以井号“#”开头,并且还包含空行。我试图让Scanner跳过这些行来获取实际信息。我无法硬编码要跳过的行数,因为输入文件可能会更改。以下是我认为可以完成我需要的代码部分:
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
if (!(line.startsWith("#")) || !(line.isEmpty())) {
outputStream.println(line);
}
}
逻辑有问题吗?我想这个代码只有非空白或不以井号开头的行会被写入我的输出文件,而是整个输入文件被写入输出文件,注释行和空行包括在内。我的猜测是我不太明白startsWith方法是如何正常工作的。欢迎任何建议,谢谢您的阅读!
修改
这是inputStream的定义位置:
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream(inputFile));
}
catch (FileNotFoundException e) {
System.out.println("File TripPlanner4_Vehicles.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
这里也是输入文件的开头,它是一个文本文件:
# Ignore blank lines and comment lines (begins with pound sign '#')
# The vertical bar '|' is used as the field delimiter within each vehicle record
# Table of Vehicle Records
# Column headings:
# Type|Make|Model|Feature(s)|Engine Size (liters)|# Cyl|Fuel Type|Tank Size (gallons)|City MPG|Hwy MPG|Towing?
Car|Chevrolet|Camaro||3.60|6|Unleaded|5.0|19|30|
Car|Chevrolet|Cruze||1.80|4|Unleaded|4.0|22|35|
Car|Chevrolet|Sonic||1.80|4|Unleaded|4.0|25|35|
编辑2
我已经提出了一种方法来完成我需要的方法,尽管这可能仅适用于我正在使用的输入文件:
while (inputStream.hasNextLine()) {
String line = inputStream.useDelimiter("|").nextLine();
if (!line.contains("#") && (line.length() > 1)) {
outputStream.println(line);
}
}
这种方法会跳过在其中包含“#”或空行的行,但是如果一行在行中的任何位置包含“#”,则会跳过它。我的输入文件只将这些放在行的开头,并且在其他地方使用,所以它适用于我的情况。如果有人有更动态的解决方案,欢迎他们分享。希望这可以帮助处于类似情况的其他人。感谢所有回复并花时间帮助的人!
答案 0 :(得分:4)
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
if (!(line.startsWith("#")) && !(line.isEmpty())) {
outputStream.println(line);
}
}
错误的运营商。更清楚:
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
if (!(line.startsWith("#") || line.isEmpty())) {
outputStream.println(line);
}
}
这就像是英文一样,不会给你带来任何错误。
答案 1 :(得分:3)
使用&&
代替||
。您想要的行不是空的,也不是以#
开头。
答案 2 :(得分:2)
打印如果它不是以#
开头,或者如果它不为空则应该有AND。
答案 3 :(得分:0)
使用
boolean startsWith= line.indexOf('#')==1;