The input file (/home/tmp/input.txt) contains multiple lines with leading spaces (indentation).
Find the number of leading spaces in the first line.
Remove that many spaces from the start of all lines, preserving relative indentation.
The input file (/home/tmp/input.txt):
first line
2nd line
something else goes here
3rd intent here
some other line
another long intent
finally the last line
So, the output file (/home/tmp/output.txt) with the modified content like the following:
first line
2nd line
something else goes here
3rd intent here
some other line
another long intent
finally the last line
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
public class MyMain {
public static void main(String... args) {
Path pIn = Path.of("/home/temp/input.txt");
Path pOut = Path.of("/home/temp/output.txt");
// Using atomic variables because we're inside a stream (lambda)
AtomicBoolean firstLine = new AtomicBoolean(true);
AtomicInteger leadingSpaces = new AtomicInteger(0);
try (Stream<String> lines = Files.lines(pIn, StandardCharsets.UTF_8);
BufferedWriter writer = Files.newBufferedWriter(pOut, StandardCharsets.UTF_8)) {
// Streams + Lambda
lines.map(line -> {
if (firstLine.get()) {
String trimmed = line.replaceFirst("^\\s*", ""); // Regex
leadingSpaces.set(line.length() - trimmed.length());
firstLine.set(false);
}
// Remove up to 'leadingSpaces' from each line; using Regex
return line.replaceFirst("^\\s{1," + leadingSpaces.get() + "}", "");
}).forEach(line -> {
try {
writer.write(line);
writer.newLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
System.out.println("File processed successfully: " + pOut);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Files.lines() → returns a Stream<String>, reading lazily (line by line).
AtomicBoolean and AtomicInteger → allow us to mutate values inside a lambda expression.
The first line determines how many leading spaces to remove (leadingSpaces).
Each line is transformed with .map(...) and written to output.txt.