Gür*_*tak 2 java file-io operating-system filewriter bufferedreader
我实现了一个从命令行获取输入文件的代码.然后,对此输入进行排序.然后将输出写入当前目录.我的代码工作,但我想知道该类型的文件.我的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
input.txt中:
xatfasfghjnvxzsdfgbsc dedd
output.txt:
aabcddddefffgghjnssst vxxz
如何以Windows格式生成输出文件(另外,它们的大小应该相同)?
您遇到的现象是UN*X系统和Microsoft Windows系统之间的行尾字符的差异.这些系统更喜欢使用不同的字符序列来表示行尾.
\nASCII中为0x0A)\r\nASCII中的0x0D和0x0A)您声明要使用Windows变体.在这种情况下,您不应该附加"\n"到新文件中的每一行.天真的方法是使用"\r\n",但有一个更好的方法:
Java使您能够获得当前平台首选的行尾字符序列.您可以通过调用System.getProperty("line.separator")(<Java 7)或System.lineSeparator()(≥Java7 )来获取平台的行尾字符序列.
因此,总结一下,您应该更改以下行:
fw.write(array[i] + "\n");
Run Code Online (Sandbox Code Playgroud)
至
fw.write(array[i] + System.lineSeparator());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1013 次 |
| 最近记录: |