【发布时间】:2026-02-01 22:45:02
【问题描述】:
我实现了一个从命令行获取输入文件的代码。然后,对该输入进行排序。然后将输出写入当前目录。我的代码有效,但我想知道那种类型的文件。 如图所示,我的 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();
}
}
}
输入.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 t v x x z
如何生成 windows 格式的输出文件(另外,它们的大小应该相同)?
【问题讨论】:
-
它们的大小不会相同,DOS 和 Unix 使用不同的行尾。在 Unix 系统上,行尾是
\n;而在 DOS/Windows 上是\r\n. -
我的愿望是使尺寸相同。是的,它们是不同的。
标签: java file-io operating-system bufferedreader filewriter