不知道这样的叫法对不对,所以对乱序两字加了个引号。代码目的是把文本文件里以行为单位的数据随机排序后存到另一个文件,速度还可以,所贴上来。测试30万行处理时间为550ms以内。
import java.io.*;
import java.util.Calendar;
public class SortTxt {
public static void main(String[] args){
Calendar frontDate =Calendar.getInstance();
try{
FileInputStream fis = new FileInputStream("c:/a.txt");
BufferedWriter wr = new BufferedWriter(new FileWriter("c:/b.txt"));
byte[] buf = new byte[fis.available()];
fis.read(buf,0,fis.available());
String str = new String(buf);
fis.close();
String[] array = str.split("\r\n");
StringBuffer sb = new StringBuffer();
sb = randomSortString(array);
wr.write(sb.toString());
wr.flush();
wr.close();
} catch (Exception e) {
e.printStackTrace();
}
Calendar rearDate = Calendar.getInstance();
System.out.println("run time: "+(rearDate.getTimeInMillis() - frontDate.getTimeInMillis())+" ms");
}
public static StringBuffer randomSortString(String[] strs) {
int size = strs.length;
StringBuffer sb = new StringBuffer();
for(int i=0;i<strs.length;i++){
int rd = (int)(Math.random()*size);
sb.append(strs[rd]+"\r\n");
strs[rd] = strs[size-1];
size--;
}
return sb;
}
}