您当前的位置: 首页 >  Gutie_bartholomew

读取文件的内容,算出计算结果,再写入文件

Gutie_bartholomew 发布时间:2018-09-26 23:30:16 ,浏览量:2

package homeworkday;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/*第五题:分析以下需求,并用代码实现
项目根路径下有个questions.txt文件内容如下:
5+5
150-25
155*155
2555/5
要求:读取内容计算出结果,将结果写入到results.txt文件中
5+5=10
//....
思考:如果说读取questions.txt文件的内容,算出计算结果,再写入questions.txt文件,即读和写的操作时针对同一个文件,应该如何操作*/
public class test5 {
 public static void main(String[] args) throws IOException, Exception {
  method();
 }//主程序末尾
 
 
 public static void method() throws IOException, Exception{//
  File f=new File("questions.txt");
  BufferedReader br=new BufferedReader(new FileReader("questions.txt"));//输入缓冲流
  String str=null;
  ArrayList al=new ArrayList();
  while((str=br.readLine())!=null){
   ScriptEngineManager manager = new ScriptEngineManager();
   ScriptEngine engine = manager.getEngineByName("js");
   //ScriptEngine getEngineByName(String shortName) 查找并创建一个给定名称的 ScriptEngine。
   //ScriptEngineManager 为 ScriptEngine 类实现一个发现和实例化机制,还维护一个键/值对集合来存储所有 Manager 创建的引擎所共享的状态。
   //ScriptEngineManager 为 ScriptEngine 类实现一个发现和实例化机制,还维护一个键/值对集合来存储所有 Manager 创建的引擎所共享的状态。
   // Object eval(String script) 执行指定的脚本。
   Object result = engine.eval(str);
   al.add(result);
  }
  br.close();
  
  PrintWriter pw = new PrintWriter("questions.txt");
  for (Object s : al) {
   pw.println(s);
  }
  pw.close();
 }
}

关注
打赏
查看更多评论

Gutie_bartholomew

暂无认证

  • 2浏览

    0关注

    350博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录