import java.util.Arrays;
/*
*
* 已知文件yuan.txt文件中的内容为“dsaofjoisjfajpajfhfjdbdsfed”,请编写程序读取该文件内容,
* 并按照自然顺序排序后输出到mu.txt文件中。
* 即b.txt中的文件内容应为“abcd…………..”这样的顺序
*
* 首先将文件都读出来
* 存到StringBuffur里,转成字符串
* 将字符串转成字符数组,
* 利用Arrays.sort(arrs);方法进行排序
* 最后将器转为字符串,输出道目标文件.
*
* 对里面的内容进行排序
*
* */
public class SortFileContent {
private BufferedReader read;
private BufferedWriter write;
private void loadFile(String fileName) throws FileNotFoundException{
FileReader in=new FileReader(fileName);
read=new BufferedReader(in);
}
private String read() throws IOException{
StringBuffer buff=new StringBuffer();
String str="";
while((str=read.readLine())!=null){
buff.append(str);
}
return buff.toString();
}
private String sort(String st){
char [] arrs = st.toCharArray();
Arrays.sort(arrs);
StringBuffer buf=new StringBuffer();
return buf.append(arrs).toString();
}
private void writer(String st)throws IOException{
write =new BufferedWriter(new FileWriter("b.txt"));
write.write(st);
write.flush();
}
private void close() throws IOException{
read.close();
write.close();
}
public void outFile() {
try {
loadFile("a.txt");
writer(sort(read()));
close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new SortFileContent().outFile();
}
}
|
|