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

it2023-04-09  73

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)