GalaxyPilot —— D.S


        生命不熄,战斗不止
数据加载中……

java “乱序”

    不知道这样的叫法对不对,所以对乱序两字加了个引号。代码目的是把文本文件里以行为单位的数据随机排序后存到另一个文件,速度还可以,所贴上来。测试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;
    }
}


posted on 2010-04-23 10:32 舵手 阅读(2173) 评论(2)  编辑  收藏

评论

# re: java “乱序”[未登录]  回复  更多评论   

Math.random()不会有重复么?
2010-04-23 17:01 | feenn

# re: java “乱序”  回复  更多评论   

Math.random() 肯定会有重复
2010-04-23 22:27 | 舵手

只有注册用户登录后才能发表评论。


网站导航: