日期:2014-05-20  浏览次数:20960 次

为什么用BufferedReader读文件每次都结果都不一样
想把双色球历史数据存入数据库。。当时想想挺简单 。可是读从网上读历史记录的时候,发现每次读出来的都不一样。
数据是http://www.17500.cn/getData/ssq.TXT。这里来的。代码
Java code

public static List<Lorry> readData(){
        String url = "http://www.17500.cn/getData/ssq.TXT";
        URL u = null;
        URLConnection conn = null;
        InputStream is = null;
        BufferedReader bReader = null;
        List<Lorry> list = new ArrayList<Lorry>();
        String[] line = null;
        try {
            u = new URL(url);
            conn = u.openConnection();
            is = conn.getInputStream();
            bReader = new BufferedReader(new InputStreamReader(is));
            while (bReader.ready()) {
                Lorry lorry = new Lorry();
//                line = bReader.readLine().split(" ");
//                lorry.setMag(line[0]);
//                lorry.setDate(line[1]);
//                lorry.setRed1(line[2]);
//                lorry.setRed2(line[3]);
//                lorry.setRed3(line[4]);
//                lorry.setRed4(line[5]);
//                lorry.setRed5(line[6]);
//                lorry.setRed6(line[7]);
//                lorry.setBlue(line[8]);
//                list.add(lorry);
                System.out.println(bReader.readLine());
            }
//            for (Lorry l : list) {
//                System.out.println(l.getDate());
//                
//            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return list;


注意每行的第二段开奖时间。控制台显示每次读到的末尾都不一样的。这是为什么啊?




------解决方案--------------------
while (bReader.ready()) {

循环条件不妥,建议用:

String line=null;
while ((line=bReader.readLine()) != null) {
------解决方案--------------------
读取结束判断应是bReader.readLine() != null
------解决方案--------------------
建议使用 Google Guava
Java code
import com.google.common.io.Resources;

List<String> records = Resources.readLines(new URL(url), Charset.forName("GBK"));