读取文件,计算文件中表达式的值

import java.io.*;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class TestMain {
	
	public static void main(String[] args) {
		TestMain tm = new TestMain();
		tm.chage();
	}
	public void chage(){
		try {
			
			/*
			 * 读取文件,计算文件中表达式的值.
			 * out.txt内容为:20*(100+8*3/6)
			 * in.txt内容为:2080.0(运行后)
			 */
			File read = new File("d:\\out.txt");
			File write = new File("d:\\in.txt");
			FileReader fr = new FileReader(read);
			FileWriter fw = new FileWriter(write);
			
			BufferedReader br = new BufferedReader(fr);
			BufferedWriter bw = new BufferedWriter(fw);
			
			String str = br.readLine();
			//貌似JDK1.6才有这个接口.
			ScriptEngine se = new ScriptEngineManager().getEngineByName("JavaScript");
			
			System.out.println(se.eval(str).toString());
			bw.write(se.eval(str).toString());
			bw.close();
			br.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}

 

你可能感兴趣的:(J2SE)