java解析txt文件并以二位数组的形式返回

java解析txt文件并以二位数组的形式返回

在我们工作中总会遇到一些解析文本文件并以二维数组的形式返回的问题,于是我提供了一个工具类供大家参考

代码如下

public class ParseUtils {
    /**
     * 
     * @param filepath 被解析txt文件地址
     * @return  String[][] 返回二维数组
     * @throws IOException
     * @throws ServiceException
     */
    public static String[][] parseTxt(String filepath) throws IOException, ServiceException {
        //声明一个二维数组
        String[][] array = null;
        //申明一个字符输入流
        FileReader fr = null;
        //申明一个字符输入缓冲流
        BufferedReader bf = null;
        //创建map数据存储电流电压值
        Map<String, Object> pams = new HashMap<>();
        try {

            //构建文本对象
            File file = new File(filepath);
            //使用文本对象构造reader对象
            fr = new FileReader(file);
            //使用reader对象构建bufferedReader对象
            bf = new BufferedReader(fr);
            //创建List集合,用来存放数据
            List<String> lists = new ArrayList<>();
            //定义字符串,记录行数据
            String str;
            //按行读取文件,对获取行数据进行处理
            while ((str = bf.readLine()) != null) {
                lists.add(str);
            }
            //获取文件行数
            int linenum = lists.size();
            //获取数组列数
            String s =  lists.get(0);
            //因为传入数据每行是以 ,为分隔符
            int columnNum = s.split(",").length;
            //申明二维数组存储数据
            array=new String[linenum][columnNum];
            //记录行数
            int count = 0;
            //遍历list集合,将集合中的数据放在数据中
            for (String list : lists) {
                //分割字符串,以", "为分隔符
                String[] strings = list.split(", ");
                //给二维数组赋值
                for(int i=0;i<count;i++){
                    array[count][i]=strings[i];
                }
                //行数加1
                count++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭字符输入缓冲流
            bf.close();
            //关闭字符输入流
            fr.close();
        }
        //返回二维数组
        return array;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值