【问题标题】:Decoding Byte Array to String and Replace String contents and encode it back?将字节数组解码为字符串并替换字符串内容并将其编码回来?
【发布时间】:2020-06-05 12:08:49
【问题描述】:

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

    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();

但它在 deorder.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】:

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

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

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

    如果是这种情况,我会更新 Utils,以便它能够正确处理丢失的文件。

    【讨论】:

      猜你喜欢
      • 2015-03-15
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 2020-05-22
      相关资源
      最近更新 更多