0

我有一个 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);
        }
    }

这种方法确实会跳过其中包含“#”的行或空白行,但是如果一行在该行的任何位置包含“#”,它将被跳过。我的输入文件只将这些放在行的开头并且没有在其他地方使用,所以它适用于我的情况。如果有人有更动态的解决方案,欢迎分享。希望这可以帮助其他有类似情况的人。感谢所有回复并花时间提供帮助的人!

4

4 回答 4

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);
        }
}

这读起来好像是英文的,不会给你带来任何可能的错误。

于 2013-11-21T00:36:30.947 回答
3

使用&&而不是||. 您需要不为空且不以 . 开头的行#

于 2013-11-21T00:36:19.730 回答
2

如果它不以 OR 开头,则打印如果它不#为空,则应该有一个 AND。

于 2013-11-21T00:36:37.420 回答
0

利用

 boolean startsWith= line.indexOf('#')==1;
于 2015-04-04T22:09:52.203 回答