字符串indent(count) – Java 中的行左缩进

字符串indent(count) – Java 中的行左缩进

原文: https://howtodoinjava.com/java12/string-left-indent-lines/

学习使用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,则在每行的开头插入的空格。
  • 负数 – 如果count < 0,则在每行的开头将删除空格。
  • 负数 – 如果count > available white spaces,则删除所有前导空格

每个空格字符都被视为一个字符。 特别是,制表符\t被视为单个字符; 它不会扩展。

2. 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();
		}
	}
}

程序输出。

        ABC
        123
        XYZ

请把关于将文件读入流的行中的问题提供给我。

学习愉快!

参考: Java 文档