Gürkan Çatak Gürkan Çatak - 2 years ago 141
Java Question

File type in java (Windows,unix)

I implemented a code that takes input file from command line. Then, sorts this input. Then write output to current directory. My code works but I am wondering that type of file.
My input.txt type is dos\Windows as seen in the picture.
My generated output.txt type is UNIX. Also their sizes are different. Why are they stored in different format? I used, bufferedReader, fileWriter to implement this code.


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.FileWriter;

public class code{

public static void main(String[] args) {

try (BufferedReader br = new BufferedReader(new FileReader(args[0])))

int lines = 0;
while (br.readLine() != null) lines++; // to get text's number of lines

String sCurrentLine;
BufferedReader br2 = new BufferedReader(new FileReader(args[0])); //to read and sort the text

String[] array; //create a new array
array = new String[lines];

int i=0;
while ((sCurrentLine = br2.readLine()) != null) {//fill array with text content
array[i] = sCurrentLine;
Arrays.sort(array); //sort array

FileWriter fw = new FileWriter("output.txt");

for (i = 0; i < array.length; i++) { //write content of the array to file
fw.write(array[i] + "\n");

System.out.println("Process is finished.");

} catch (IOException e) {



x a t f a s f g h j n v x z s d f g b s c d e d d

output.txt :

a a b c d d d d e f f f g g h j n s s s t v x x z

SS-s enter image description here

enter image description here

How can I generate output file as windows format(Also,their sizes should be same)?

Answer Source

The phenomenon you are experiencing is a difference in end-of-line characters between UN*X systems and Microsoft Windows systems. These systems prefer to use different sequences of characters to signal a end of line.

  • UN*X systems use the LF (line feed) character (\n, 0x0A in ASCII)
  • Windows systems use a CR (carriage return) and a LF (line feed) character (\r\n, 0x0D and 0x0A in ASCII)

You state that you want to use the Windows variant. In that case, you should not be appending "\n" to every line in the new file. The naive approach would be to use "\r\n\", but there is a better way:

Java provides you with the ability to get your current platform's preferred end-of-line character sequence. You can get your platform's end-of-line character sequence by calling System.getProperty("line.separator") (< Java 7) or System.lineSeparator() (≥ Java 7).

So, to sum this up, you should change the following line:

fw.write(array[i] + "\n");


fw.write(array[i] + System.lineSeparator());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download