import java.io.*;
class FileChar{
private String str;
private char arrayList[];
private BufferedReader br;//字符
private File f; //文件
FileChar(String s) {
f=new File(s);
}
public void start(){
if( inputData()==-1 ){
return;
}
sortChar();
//把排序的字符数组编程字符串,写入b.txt.
outputString();
}
//字符数组冒泡排序
private void sortChar(){
char temp=0;
for( int i=0; i<arrayList.length-1; i++ ){
for( int j=0; j<arrayList.length-i-1; j++ ){
if( arrayList[j]>arrayList[j+1] ){
temp=arrayList[j];
arrayList[j]=arrayList[j+1];
arrayList[j+1]=temp;
}
}
}
}
private int inputData(){
try{
br=new BufferedReader( new FileReader(f));
while( (str=br.readLine())!=null ){
str.toLowerCase();//所有大写字母转换小写
arrayList=str.toCharArray();
}
}
catch(IOException e){
System.out.println( "读取文件出错!" );
e.printStackTrace();
return -1;
}
finally{
if(br!=null) {
try{
br.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
return 1;
}
private void outputString(){
BufferedWriter bw=null;
try{
FileWriter fw = new FileWriter("b.txt");
bw = new BufferedWriter(fw);
bw.write( new String( arrayList,0,arrayList.length ));
bw.flush();//flush 的常规协定是:如果此输出流的实现已经缓冲了以前写入的任何字节,则调用此方法指示应将这些字节立即写入它们预期的目标。
}
catch(IOException e){
e.printStackTrace();
}
finally{
if(bw!=null){
try{
bw.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
}
public class Demo{
public static void main(String arsg[]){
new FileChar( "a.txt" ).start();
System.out.println("排序已完成,请看b.txt文件");
}
}
|