将字节数组解码为字符串并替换字符串内容并将其编码回去吗?

问题描述 投票:0回答:1

我有一个字节数组,我想将单词“ 404”替换为“ replaced”。我尝试了这段代码:

    byte[] fileData = Utils.readFileData(file, filelength);



    CharsetDecoder decoder = StandardCharsets.US_ASCII.newDecoder();

    decoder.onMalformedInput(CodingErrorAction.REPLACE);
    decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    decoder.replaceWith("?");

    String string = decoder.decode(ByteBuffer.wrap(fileData)).toString();

    string = string.replace("404", "replaced");

    fileData = string.getBytes();

但是它会在decorder.decode()上抛出并出错:

Exception in thread "Thread-0" java.lang.NullPointerException
    at java.nio.ByteBuffer.wrap(Unknown Source)
    at de.cfp.webserver.ReturnAnswer.ok(ReturnAnswer.java:70)
    at de.cfp.webserver.WebServer.run(WebServer.java:93)
    at java.lang.Thread.run(Unknown Source)

所以,是吧?现在怎么办?

java arrays string byte
1个回答
0
投票

NullPointerExceptoin的最可能原因是fileData为null。

您可以检查Utils.readFileData(file,filelength);返回null?您可以在Utils.readFileData之后添加检查。这有助于调试。

byte[] fileData = Utils.readFileData(file, filelength);
if (fileData == null) throw new RuntimeException("The file is " + file.getName() + " could not be read");

如果是这种情况,我将更新实用程序,以便它可以正确处理丢失的文件。

© www.soinside.com 2019 - 2024. All rights reserved.