Java包装UTF-8文本?

Rom*_*man 1 java utf-8 word-wrap

我需要简单地包装长文本以几行显示它.我尝试了默认代码段:

String s = "Español texto aquí";
StringBuilder sb = new StringBuilder(s);

int i = 0;
while (i + 20 < sb.length() && (i = sb.lastIndexOf(" ", i + 20)) != -1) {
sb.replace(i, i + 1, "\n");
}

System.out.println(sb.toString());
Run Code Online (Sandbox Code Playgroud)

但是对于西班牙语文本,输出中出现错误的符号.如何包装非英文文本?

Mar*_*nik 5

String s = "Español texto aquí texto aquí Español texto aquí";
StringBuilder sb = new StringBuilder(s);

int i = 0;
while (i + 20 < sb.length() && (i = sb.lastIndexOf(" ", i + 20)) != -1) {
  sb.replace(i, i + 1, "\n");
}

System.out.println(sb.toString());
Run Code Online (Sandbox Code Playgroud)

版画

Español texto aquí
texto aquí Español
texto aquí
Run Code Online (Sandbox Code Playgroud)

现在,我没有看到任何错误.