gpt4 book ai didi

java - java读取文件时如何转义以特殊字符开头的行

转载 作者:行者123 更新时间:2023-12-02 00:09:30 25 4
gpt4 key购买 nike

假设一个文件包含以下几行:

#Do
#not
#use
#these
#lines.

Use
these.

我的目标是只读取那些不以#开头的行。如何在 Java 中以最佳方式完成此操作?

最佳答案

假设您想要累积行(当然您可以对每一行执行所有操作)。

String filePath = "somePath\\lines.txt";

// Lines accumulator.
ArrayList<String> filteredLines = new ArrayList<String>();

BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
String line;

while ((line = bufferedReader.readLine()) != null) {
// Line filtering. Please note that empty lines
// will match this criteria!
if (!line.startsWith("#")) {
filteredLines.add(line);
}
}
}
finally {
if (bufferedReader != null)
bufferedReader.close();
}

使用 Java 7 try-with-resources 语句:

String filePath = "somePath\\lines.txt";
ArrayList<String> filteredLines = new ArrayList<String>();

try (Reader reader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(reader)) {

String line;
while ((line = bufferedReader.readLine()) != null) {
if (!line.startsWith("#"))
filteredLines.add(line);
}
}

关于java - java读取文件时如何转义以特殊字符开头的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13128494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com