进度2

本周收获:

获取一定范围内的随机数:

public static int random_num(int a,int b)
    {
        int c=(int) (Math.random()*(b-a+1));
        return c+a;
    }

将信息写入到TXT文档(数据之间用空格隔开):

public static void WriterFun(){
        //获得路径
        File file = new File("input.txt");
        if(!file.exists()){//判断file是否存在
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            for(int i=0;i<10000;i++){
                int nums = random_num(-1000000,2000000);
                //将int 转化为 String类型
                if(i!=0)
                    bw.write(" "+Integer.toString(nums));
                else bw.write(Integer.toString(nums));
                //bw.newLine();
            }
            bw.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

从文件中读取数据(并用正则表达式判断数据是否符合标准):

        String pathname = "input.txt";
        try ( FileReader reader = new FileReader(pathname);
                BufferedReader br = new BufferedReader(reader) 
                ){
            String line;
            while ((line = br.readLine()) != null) {
                // 一次读入一行数据
                String []strlist=line.split(" ");//按空格来拆分字符串
                for(String it:strlist)
                {
                    Pattern p=Pattern.compile("-?[0-9]*");//表示“-”可有可无每一位上的数字都是0-9这10个数字
            //“*”匹配前面的子表达式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"。 Matcher m
=p.matcher(it); if(m.matches()) { int i; i=Integer.parseInt(it); shuzu.add(i); } else { System.out.println("文件中含有非法字符"); return; } }
原文地址:https://www.cnblogs.com/janeszj/p/10545873.html