How to set or change line endings of a text file in Java

Cloudmersive
2 min readAug 6, 2020

--

Line ending issues can cause some serious headaches if you don’t have an easy method for unifying them. In this tutorial we will demonstrate how this can be accomplished quickly and easily. After minimal setup and just a single function call, you will never have to worry about your line endings again!

First comes our repository reference, like so:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

And next after that, our dependency reference:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.54</version>
</dependency>
</dependencies>

Now it’s time to call our function for changing line endings. This will just need our input file and desired line ending format by operating system:

// Import classes://import com.cloudmersive.client.invoker.ApiClient;//import com.cloudmersive.client.invoker.ApiException;//import com.cloudmersive.client.invoker.Configuration;//import com.cloudmersive.client.invoker.auth.*;//import com.cloudmersive.client.EditTextApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: ApikeyApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");Apikey.setApiKey("YOUR API KEY");// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)//Apikey.setApiKeyPrefix("Token");EditTextApi apiInstance = new EditTextApi();String lineEndingType = "lineEndingType_example"; // String | Required; 'Windows' will use carriage return and line feed, 'Unix' will use newline, and 'Mac' will use carriage returnFile inputFile = new File("/path/to/file.txt"); // File | Input file to perform the operation on.try {ChangeLineEndingResponse result = apiInstance.editTextChangeLineEndings(lineEndingType, inputFile);System.out.println(result);} catch (ApiException e) {System.err.println("Exception when calling EditTextApi#editTextChangeLineEndings");e.printStackTrace();}

And there you have it! Done.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet