Java 示例 - 字符串缓冲 问题描述 如何缓冲字符串? 解决方案 下面的示例缓冲字符串并使用emit() 方法刷新它。 public class StringBuffer { public static void main(String[] args) { countTo_N_Improved(); } private final static int MAX_LENGTH = 30; private static String buffer = ""; private static void emit(String nextChunk) { if(buffer.length() + nextChunk.length() > MAX_LENGTH) { System.out.println(buffer); buffer = ""; } buffer += nextChunk; } private static final int N = 100; private static void countTo_N_Improved() { for (int count = 2; count <= N; count = count +2) { emit(" " + count); } } } 复制 结果 上面的代码示例将产生以下结果。 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 复制 StringBuffer 和 StringBuilder 类用于创建可变字符串。 字符串缓冲区 public class HelloWorld { public static void main(String []args) { StringBuffer sb = new StringBuffer("hello"); sb.append("world"); sb.insert(0, " Tutorialspoint"); System.out.print(sb); } } 复制 结果 上面的代码示例将产生以下结果。 Tutorialspointhelloworld 复制