String indent(count) – Left indent lines in Java

Learn to indent (left indentation) a string(s) in Java using String.indent() API. This api has been introduced in Java 12.

1. String.indent(count) API

This method adjusts the indentation of each line of a given string based on the value of count, and normalizes line termination characters.

/**
* 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)

Note that the value of count can be either positive or nagative number.

  • positive number – If count > 0 then spaces are inserted at the beginning of each line.
  • negative number – If count < 0 then spaces are removed at the beginning of each line.
  • negative number – If count > available white spaces then all leading spaces are removed.

Each white space character is treated as a single character. In particular, the tab character “\t” is considered a single character; it is not expanded.

2. String.indent​() Example

Java program to white strings into file indented to 8 characters.

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

Program output.

        ABC
        123
        XYZ

Drop me your questions related to reading a file into lines of stream.

Happy Learning !!

Ref : Java doc

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.