学习使用String.indent() API在Java中缩进(左缩进)字符串。 该API已在Java 12引入。
1. String.indent(count) API
此方法根据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的值可以是正数或负数。正数–如果count > 0则在每行的开头inserted空格。
负数–如果count < 0则在每一行的开头removed空格。
负数–如果count > available white spaces则所有前导空格都removed被removed 。每个空格字符都被视为一个字符。 特别是,制表符“ t”被视为单个字符; 它不会扩展。
2. String.indent() Example
Java程序将白色字符串转换成缩进8个字符的文件。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 lines = Files.lines(file);
lines.forEach(System.out::println);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Program output.ABC
123
XYZ
将有关将文件读入流中的问题,请问我。
最后
以上就是跳跃星星最近收集整理的关于java leftcount,String indent(count) - Left indent lines in Java - 入门小站-rumenz.com的全部内容,更多相关java内容请搜索靠谱客的其他文章。
发表评论 取消回复