[英]Decoding Byte Array to String and Replace String contents and encode it back?
我有一个字节数组,我想用“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)
所以,嗯? 现在该怎么做?
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");
如果是这种情况,我会更新 Utils,以便它可以错误地处理丢失的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.