学习使用 String.indent() API在Java中缩进(左缩进)字符串。此API已在 Java 12 中引入。
此方法根据count的值调整给定字符串的每一行的缩进,并标准化行终止符。
/** * count - number of leading white space characters to add or remove * returns - string with indentation adjusted and line endings normalized */ public String indent(int count)
请注意,
count > 0
然后在每行的开头插入空格。count < 0
然后在每行的开头删除空格。count > available white spaces
然后删除所有前导空格。每个空格字符都被视为一个字符。特别是,制表符" \ t"被视为单个字符;它不会扩展。
Java程序将白色字符串转换成缩进8个字符的文件。
链接:https://www.learnfk.comhttps://www.learnfk.com/java/java12-string-left-indent-lines.html
来源:LearnFk无涯教程网
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.stream.Stream; public class Main { public static void main(String[] args) { try { Path file = Files.createTempFile("testOne", ".txt"); //Write strings to file indented to 8 leading spaces Files.writeString(file, "ABC".indent(8), StandardOpenOption.APPEND); Files.writeString(file, "123".indent(8), StandardOpenOption.APPEND); Files.writeString(file, "XYZ".indent(8), StandardOpenOption.APPEND); //Verify the content Stream<String> lines = Files.lines(file); lines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } }
程序输出。
ABC 123 XYZ
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕