在下面的代码中,我有一个ByteArrayOutputStream,我正在尝试循环,目标是尝试替换HTML等效的&用“&”性格本身。我正在尝试纠正的问题是HTML值正在日志中打印,我需要用“&”来纠正它。在我的日志中打印这个代码的代码在下面,这是我尝试过但这不起作用。
任何帮助将不胜感激。谢谢。
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream pStream = new PrintStream(baos);
receivedIsoMessage.dumpMsg(pStream, "Message received:");
for (final String logString : baos.toString().split("\n")) {
if (baos.toString().contains("&")) {
logString.replace("&", "&");
}
LOGGER.info(logString.replaceAll("(\\r|\\n)", ""));
}
答案 0 :(得分:1)
String.replace()
会返回一个新字符串,但您要丢弃它。
试试这个
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream pStream = new PrintStream(baos);
receivedIsoMessage.dumpMsg(pStream, "Message received:");
for (String logString : baos.toString().split("\n")) {
if (baos.toString().contains("&")) {
logString = logString.replace("&", "&");
}
LOGGER.info(logString.replaceAll("(\\r|\\n)", ""));
}
编辑:正如评论中所述,此代码有一些不必要的检查,可以简化。例如,整个for循环可以用一行代替:
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream pStream = new PrintStream(baos);
receivedIsoMessage.dumpMsg(pStream, "Message received:");
LOGGER.info(baos.toString().replaceAll("&", "&").replaceAll("(\\r|\\n)", ""));
答案 1 :(得分:1)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream pStream = new PrintStream(baos);
receivedIsoMessage.dumpMsg(pStream, "Message received:");
for (String logString : baos.toString().split("\n")) {
if (logString.contains("&")) { // or just remove the if statement like Sam mentioned
logString = logString.replace("&", "&");
}
LOGGER.info(logString.replaceAll("(\\r|\\n)", ""));
}
答案 2 :(得分:1)
Java字符串是不可变的。
logString.replace("&", "&");
什么都不做。试试
String newString=logString.replace("&", "&");
LOGGER.info(newString.replaceAll("(\\r|\\n)", ""));