簡體   English   中英

java中的文件類型(Windows,unix)

[英]File type in java (Windows,unix)

我實現了一個從命令行獲取輸入文件的代碼。 然后,對此輸入進行排序。 然后將輸出寫入當前目錄。 我的代碼工作,但我想知道該類型的文件。 我的input.txt類型是dos \\ Windows,如圖所示。 我生成的output.txt類型是UNIX。 它們的尺寸也不同。 為什么它們以不同的格式存儲? 我使用bufferedReader,fileWriter來實現這段代碼。

code.java:

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;
                i++;
            }
            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");
            }
            fw.close();


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


        } catch (IOException e) {
            e.printStackTrace();
        } 

    }
}

input.txt中:

xatfasfghjnvxzsdfgbsc dedd

output.txt:

aabcddddefffgghjnssst vxxz

SS-S 在此輸入圖像描述

在此輸入圖像描述

如何以Windows格式生成輸出文件(另外,它們的大小應該相同)?

您遇到的現象是UN * X系統和Mi​​crosoft Windows系統之間的行尾字符的差異。 這些系統更喜歡使用不同的字符序列來表示行尾。

  • UN * X系統使用LF(換行)字符(ASCII中為\\n ,0x0A)
  • Windows系統使用CR(回車)和LF(換行)字符(ASCII中的\\r\\n ,0x0D和0x0A)

您聲明要使用Windows變體。 在這種情況下,您不應將"\\n"附加到新文件中的每一行。 天真的方法是使用"\\r\\n" ,但有更好的方法:

Java使您能夠獲得當前平台首選的行尾字符序列。 您可以通過調用System.getProperty("line.separator") (<Java 7)或System.lineSeparator()System.lineSeparator()來獲取平台的行尾字符序列。

因此,總結一下,您應該更改以下行:

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

fw.write(array[i] + System.lineSeparator());

Windows上的行結尾與其他平台上的行結尾不同。 你總是寫"\\n"這是Unix行的結尾。

雖然您可以簡單地將其硬編碼到Windows行結尾( "\\r\\n" ),但如果您希望代碼可以在任何地方使用,則應使用平台行分隔符。 一種方法是從系統屬性獲取它:

fw.write(array[i] + System.getProperty("line.separator"));

稍微更易讀的方法是用Formatter替換FileWriter:

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

for (i = 0; i < array.length; i++) { //write content of the array to file
    fw.format("%s%n", array[i]);
}
fw.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM