【问题标题】:Reading file as bytes without newline or carriage return将文件作为字节读取,没有换行符或回车符
【发布时间】:2018-05-10 16:31:10
【问题描述】:

我想将整个文件读入一个不带换行符或回车符的字节数组。我在字节数组中也得到了 13,10。有没有办法在没有换行符或回车的情况下读取整个文件。 我使用了以下代码:

InputStream in = new FileInputStream(file);
numBytesRead=in.read(result, offset, noBytes);

还有其他方法吗?

【问题讨论】:

    标签: java


    【解决方案1】:

    据我所知,您必须自己过滤:

    byte[] raw = Files.readAllBytes(file.toPath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (byte b : raw)
        if (b != 10 && b != 13)
            baos.write(b);
    byte[] result = baos.toByteArray();
    

    【讨论】:

    • 谢谢。除了 10 和 13 之外,还有什么需要过滤的,因为我是新来将文件作为字节处理的。
    • 我不知道,你没有提供足够的信息。你想做什么?
    • 我想将记录(size-160)中的每第二个和第三个字节替换为空格。
    • private void readInBytes(File file, int byteBlockSize) throws IOException { byte[] raw = Files.readAllBytes(file.toPath()); ByteArrayOutputStream baos = new ByteArrayOutputStream();诠释 i = 0; for(byte b: raw) { if (i == 2 || i == 3) b = 32;如果 (b != 10 && b != 13 ) { i++; } if (i > byteBlockSize) i = 0; baos.write(b); System.out.print(b + ","); } }
    • 所以你有一个记录文件,其中每个是 160 字节,后跟 CR LF?
    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 2019-05-29
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多