我有一个字节数组,我想将单词“ 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)
所以,是吧?现在怎么办?
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");
如果是这种情况,我将更新实用程序,以便它可以正确处理丢失的文件。