欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将文件中的数字复制到另一个文件

程序员文章站 2022-07-11 09:09:04
...

代码如下:

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Solution {
    public static void main(String[] args) throws Exception{
        PanDuan t = new PanDuan();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String name1 = reader.readLine();
        String name2 = reader.readLine();
        reader.close();
        FileReader file1 = new FileReader(name1);
        BufferedReader fis = new BufferedReader(file1);
        FileWriter file2 = new FileWriter(name2);
        BufferedWriter fox = new BufferedWriter(file2);

        String data = "";
        String[] tem = null;
        while (fis.ready()){
            data =fis.readLine();
            tem = data.split(" ");
        }
        for(String a :tem) {
            if (t.isNumeric(a) == true) {
                fox.write(a+" ");
                fox.flush();
            }
        }
        fox.close();
        fis.close();

    }

    private static class PanDuan {
        public boolean isNumeric(String str){
            Pattern pattern = Pattern.compile("[0-9]*");
            Matcher isNum = pattern.matcher(str);
            if( !isNum.matches() ){
                return false;
            }
            return true;
        }
    }
}

name1 为目标文件对象,name2 为要得到的文件对象。

相关标签: java java