gpt4 book ai didi

java - java中的文件类型(Windows,unix)

转载 作者:行者123 更新时间:2023-12-02 09:24:18 25 4
gpt4 key购买 nike

我实现了一个从命令行获取输入文件的代码。然后,对该输入进行排序。然后将输出写入当前目录。我的代码有效,但我想知道那种类型的文件。我的 input.txt 类型是 dos\Windows,如图所示。我生成的output.txt类型是UNIX。它们的大小也不同。为什么它们以不同的格式存储?我使用了bufferedReader、fileWriter来实现这段代码。

代码.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();
}

}
}

输入.txt:

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

输出.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

如何生成 Windows 格式的输出文件(而且它们的大小应该相同)?

最佳答案

您遇到的现象是 UN*X 系统和 Microsoft Windows 系统之间的行尾字符存在差异。这些系统更喜欢使用不同的字符序列来表示行结束。

  • UN*X 系统使用 LF(换行)字符(\n,ASCII 中的 0x0A)
  • Windows 系统使用 CR(回车)和 LF(换行)字符(\r\n、ASCII 中的 0x0D 和 0x0A)

您声明您想要使用 Windows 变体。在这种情况下,您不应将 "\n" 附加到新文件中的每一行。简单的方法是使用 "\r\n",但还有更好的方法:

Java 使您能够获取当前平台的首选行尾字符序列。您可以通过调用 System.getProperty("line.separator") (< Java 7) 或 System.lineSeparator() ( ≥ Java 7)。

因此,总而言之,您应该更改以下行:

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

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

关于java - java中的文件类型(Windows,unix),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37061234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com