如何在Java中分割包含多个“行”的字节数组?

Dra*_*max 2 java arrays loops newline line

假设我们有一个像这样的文件:

one 
two 
three
Run Code Online (Sandbox Code Playgroud)

(但是这个文件被加密了)

我的加密方法以 byte[] 类型返回内存中的整个文件。
我知道字节数组没有“行”的概念,这是扫描仪(例如)可以拥有的概念。

我想遍历每一行,将其转换为字符串并对其执行操作,但我不知道如何:

  1. 查找字节数组中的行
  2. 将原始字节数组切片为“行”(我会将这些切片转换为字符串,以发送到我的其他方法)
  3. 正确遍历字节数组,其中每次迭代都是一个新的“行”

另外:我是否需要考虑文件可能组成的不同操作系统?我知道 Windows 和 Linux 中的新行之间存在一些差异,我不希望我的方法仅适用于一种格式。

编辑:根据此处答案的一些提示,我能够编写一些代码来完成工作。我仍然想知道这段代码是否值得保留,或者我正在做的事情将来可能会失败:

byte[] decryptedBytes = doMyCrypto(fileName, accessKey);
ByteArrayInputStream byteArrInStrm = new ByteArrayInputStream(decryptedBytes);
InputStreamReader inStrmReader = new InputStreamReader(byteArrInStrm);
BufferedReader buffReader = new BufferedReader(inStrmReader);

String delimRegex = ",";
String line;
String[] values = null;

while ((line = buffReader.readLine()) != null) {
    values = line.split(delimRegex);
    if (Objects.equals(values[0], tableKey)) {
        return values;
    }
}
System.out.println(String.format("No entry with key %s in %s", tableKey, fileName));
return values;
Run Code Online (Sandbox Code Playgroud)

特别是,我被建议显式设置编码,但我无法确切地看到在哪里?

Jon*_*eet 7

如果你想直播这个,我建议:

  • 创建一个ByteArrayInputStream来包装您的数组
  • 将其包装在 an 中InputStreamReader以将二进制数据转换为文本 - 我建议您明确指定正在使用的文本编码
  • 围绕它创建一个BufferedReader以一次读取一行

然后你就可以使用:

String line;
while ((line = bufferedReader.readLine()) != null)
{
    // Do something with the line
}
Run Code Online (Sandbox Code Playgroud)

BufferedReader处理所有操作系统的换行符。

所以像这样:

String line;
while ((line = bufferedReader.readLine()) != null)
{
    // Do something with the line
}
Run Code Online (Sandbox Code Playgroud)

请注意,通常您希望对流和读取器使用 try-with-resources 块 - 但在这种情况下并不重要,因为它只是在内存中。