Java UnixLineEndingInputStream-class And Method Code Example


Here is an example of how to use the UnixLineEndingInputStream class from the Apache Commons IO library to convert Windows line endings to Unix line endings while reading from an input stream in Java:

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.input.UnixLineEndingInputStream;

public class LineEndingConversionExample {
    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = new FileInputStream("path/to/file.txt");
        UnixLineEndingInputStream unixStream = new UnixLineEndingInputStream(inputStream);
        int data;
        while ((data = unixStream.read()) != -1) {
            // Do something with the data, for example, write it to a file or display it on the console
            System.out.print((char) data);
        }
        unixStream.close();
        inputStream.close();
    }
}

In this example, a FileInputStream is created to read from a file located at "path/to/file.txt". This input stream is then wrapped with a UnixLineEndingInputStream, which will convert any Windows line endings (CR+LF) to Unix line endings (LF) while the data is read.

A while loop is used to read the data from the input stream and it is displayed on the console. The unixStream.read() method returns -1 when the end of the stream is reached.

Finally, all the streams are closed after reading the file.

This can be useful when working with files that may have been created or edited on systems that use different line ending conventions, such as Windows and Unix-based systems.