java 使用 String.indent() 实现左缩进
更多: zhilu jiaocheng

String.indent() 示例

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<String> lines = Files.lines(file);
			lines.forEach(System.out::println);
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}

Java 12 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则在每行的开头插入空格。
  • 负数 - 如果 count < 0则在每行开头删除空格。
  • 负数 - 如果count > 可用空格,则删除所有前导空格。

每个空白字符都被视为单个字符。
特别地,制表符“\t”被认为是单个字符;它没有扩展。

日期:2020-09-17 00:09:45 来源:oir作者:oir