gpt4 book ai didi

java - 如何使 InputStream 跳过以 '#' 开头的行?

转载 作者:行者123 更新时间:2023-12-02 13:42:35 24 4
gpt4 key购买 nike

我正在编写一个必须解码二维码的程序。这些代码在内部表示为二维 boolean 列表。这些代码通常会被读取为包含 1 和 0 的文本文件,其中 1 表示矩阵中的暗模块(真),0 表示亮模块(假)。

我必须实现一个方法,该方法将接受一个输入流,然后必须返回一个二维码。我必须读取包含 1、0 和以“#”开头的注释行的 .txt。我需要使该方法忽略这些注释行,但我不知道该怎么做。

以下是代码的一些相关部分:

首先是 QR 码构造函数(构造函数中使用的所有方法都起作用并完成其工作):

public class QRCode {

private List<List<Boolean>> data; //A 2D Boolean matrix, true means black, false means white.

public QRCode(List<List<Boolean>> data)
{
if (data == null)
throw new NullPointerException();
if (QRCode.isQuadratic(data) == false)
throw new InvalidQRCodeException("Matrix must be quadratic!");
if (QRCode.versionCheck(data) < 1 || QRCode.versionCheck(data) > 40)
throw new InvalidQRCodeException("Invalid Dimensions (Version).");
if (QRCode.correctlyAlligned(data) != true)
throw new InvalidQRCodeException("Improper Allignment!");
if (QRCode.correctTimers(data) != true)
throw new InvalidQRCodeException("Incorrect Timing Pattern!");
if (QRCode.correctFormatting(data) != true)
throw new InvalidQRCodeException("Incorrect Formatting!");

this.data = data;
}

}

这就是我指的方法。至少到目前为止我写的。此外,如果 .txt 文件包含除 1、0 和注释以外的任何内容,它应该引发异常。PS:我以前从未使用过InputStreams,我尝试用谷歌搜索这个,但我发现的所有答案都是针对特定类型的流,并且它们使用 .readLine() 方法,我在这里不允许我使用该方法。

public static QRCode fromFile(InputStream is) throws IOException 
{
int i;
List<List<Boolean>> data = new ArrayList<>(); //a 2D Boolean Matrix
int y = -1, x = -1;

if (is == null)
throw new NullPointerException();
while((i = is.read())!=-1) //Reading begin
{
if (i == (byte) '\n') //If a line in .txt file ends.
{
y++;
data.add(new ArrayList<Boolean>());
x = 0;
}

if ((char) i == '1') //|| (char) i == '0')
{
data.get(y).add(true);
x++;
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 1 0 1 1 0 0 1
1 0 0 0 0 0 1 0 0 0 1 1 0 1 1 0 1 0 0 0 1 1 0 0 0
1 0 1 1 1 0 1 0 1 0 0 1 0 1 0 1 1 1 1 1 1 1 0 1 1
1 0 1 1 1 0 1 0 1 0 0 0 1 1 1 0 0 1 1 0 0 0 1 1 1
1 0 1 1 1 0 1 0 0 0 1 1 0 1 0 0 1 1 0 1 1 0 0 1 1
1 0 0 0 0 0 1 0 1 0 1 1 1 1 0 0 0 0 1 1 0 1 1 1 1
1 1 1 1 1 1 1 0 1 0 1 1 1 1 0 0 1 0 1 0 0 1 0 0 1

最佳答案

首先,我建议您使用Reader来阅读文本。然后,您可以使用 BufferedReader 及其 readLine() 方法来处理文本行,而不是字节流。

<小时/>

无论如何,给定您当前的代码:一旦您读取了 \n,请设置一个 boolean 标志以指示您刚刚看到了一个新行字符。然后,当您开始阅读下一行时,打开该标志,如果它为真,并且您看到 # 作为下一个字符,则应该阅读直到看到另一个 \n。如果标志不为 true,则按照您正在执行的操作读取该行的其余部分。

在查找 # 时,您可能需要考虑空格,具体取决于您希望其宽松程度。

关于java - 如何使 InputStream 跳过以 '#' 开头的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42657295/

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