我想将文本保存到文件中,以便某些段落缩进(段落的每一行都缩进)。我使用的是BufferedWriter或Scanner之类的东西。如果不计算字符数,我该怎么做呢?
发布于 2011-08-11 04:33:45
您必须找到所有换行符,并在每个换行符后面插入适当数量的空格。
因此,代码总是需要查看每个字符,并且可能还需要解析文本,以便找出缩进的位置和缩进量。
您可以实现处理解析和格式化的java.io.Writer。尽管最有效的方法是直接在char buffer上工作,但它也比仅仅创建一个新的字符串并使用字符串函数复杂得多,因此通常最好的做法是先追求稳定性,然后再考虑效率。
如果整个文件的缩进都是相同的,那么可以执行一个简单的String.replaceAll(),并将换行符替换为换行符后跟一些空格。如果你需要动态缩进,你可能需要分析(查找)缩进级别发生变化的地方,检查每个字符的换行符或缩进级别是否发生了变化,现在购买它变得越来越复杂……
发布于 2016-03-01 01:50:35
这里有一个解决方案。这种方法用缩进替换了所有换行符。缩进一个级别需要一个indent()调用。要取消缩进,请调用unindent()方法。
public class IndentPrintWriter extends java.io.PrintWriter
{
private boolean newLine;
private String singleIndent = " ";
private String currentIndent = "";
public IndentPrintWriter(Writer pOut, String indent)
{
super(pOut);
this.singleIndent = indent;
}
public void indent()
{
currentIndent += singleIndent;
}
public void unindent()
{
if (currentIndent.isEmpty()) return;
currentIndent = currentIndent.substring(0, currentIndent.length() - singleIndent.length());
}
@Override
public void print(String pString)
{
// indent when printing at the start of a new line
if (newLine)
{
super.print(currentIndent);
newLine = false;
}
// strip the last new line symbol (if there is one)
boolean endsWithNewLine = pString.endsWith("\n");
if (endsWithNewLine) pString = pString.substring(0, pString.length() - 1);
// print the text (add indent after new-lines)
pString = pString.replaceAll("\n", "\n" + currentIndent);
super.print(pString);
// finally add the stripped new-line symbol.
if (endsWithNewLine) println();
}
@Override
public void println()
{
super.println();
newLine = true;
}
}https://stackoverflow.com/questions/7016896
复制相似问题