[英]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
如何以Windows格式生成输出文件(另外,它们的大小应该相同)?
您遇到的现象是UN * X系统和Microsoft Windows系统之间的行尾字符的差异。 这些系统更喜欢使用不同的字符序列来表示行尾。
\\n
,0x0A) \\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.