从一个文件读取内容计算出结果,将结果写入到另一个文件中

来源:互联网 发布:用js做一个登录界面 编辑:程序博客网 时间:2024/05/17 06:36
/* * 项目根路径下有个questions.txt文件内容如下:5+5 [ 5, 5]150-25155*1552555/5要求:读取内容计算出结果,将结果写入到results.txt文件中 */public class Test5 {public static void main(String[] args) throws IOException {//高效字符流来读取文件BufferedReader br = new BufferedReader(new FileReader("questions.txt"));//创建集合对象ArrayList<String> als = new ArrayList<String>();//读数据String line;while ((line =  br.readLine()) != null) {//我把这些读到的数据写到集合中als.add(line);}//获得集合的0号索引元素String str1 = als.get(0);//切割这个元素String[] split1 = str1.split("\\+");//String ==> intint result1 = Integer.parseInt(split1[0]) + Integer.parseInt(split1[1]);//写数据 字符输出流BufferedWriter bw = new BufferedWriter(new FileWriter("result.txt"));//那我就拼字符串bw.write(str1+"="+result1 + "");bw.newLine();//获得集合的1号索引元素String str2 = als.get(1);//切割这个元素String[] split2 = str2.split("\\-");//String ==> intint result2 = Integer.parseInt(split2[0]) - Integer.parseInt(split2[1]);//那我就拼字符串bw.write(str2+"="+result2 + "");bw.newLine();//获得集合的2号索引元素String str3 = als.get(2);//切割这个元素String[] split3 = str3.split("\\*");//String ==> intint result3 = Integer.parseInt(split3[0]) * Integer.parseInt(split3[1]);//那我就拼字符串bw.write(str3+"="+result3 + "");bw.newLine();//获得集合的3号索引元素String str4 = als.get(3);//切割这个元素String[] split4 = str4.split("\\/");//String ==> intint result4 = Integer.parseInt(split4[0]) / Integer.parseInt(split4[1]);//那我就拼字符串bw.write(str4+"="+result4 + "");bw.newLine();br.close();bw.close();}}

阅读全文
0 0