Android 由于安卓中没有ScriptEngineManager ,需要增加依赖
implementation 'io.apisense:rhino-android:1.1.1'
function convert (str)
{
var res = encodeURI(str);
return res;
}
import org.springframework.core.io.ClassPathResource;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.*;
/**
* @author reshui
* @version 1.0
* @date 2021/12/10
*/
public class JsUtil {
public static void main(String[] args) throws Exception {
String x="my test.asp?name=ståle&car=saab";
testJSFile(x);
}
public static String testJSFile(String str) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("javascript");
engine.eval(readJSFile());
Invocable inv = (Invocable) engine;
Object res = (Object) inv.invokeFunction("convert", new String[] { str });
System.out.println("res:" + res);
return (String) res;
}
/**
* 文件流读取js
* @return
* @throws IOException
*/
private static String readJSFile() throws IOException {
//maven工程resources/js/c.js
ClassPathResource resource = new ClassPathResource("js/"+"c.js");
StringBuffer script = new StringBuffer();
//获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
InputStream inputStream = resource.getInputStream();
BufferedReader bufferreader = new BufferedReader(new InputStreamReader(inputStream));
String tempString = null;
while ((tempString = bufferreader.readLine()) != null) {
script.append(tempString).append("\n");
}
bufferreader.close();
inputStream.close();
return script.toString();
}
/**
* 字符文件读取
* @return
* @throws Exception
*/
private static String readJSFilex() throws Exception {
StringBuffer script = new StringBuffer();
File file = new File("C:\\Users\\acer\\Desktop\\c.js");
FileReader filereader = new FileReader(file);
BufferedReader bufferreader = new BufferedReader(filereader);
String tempString = null;
while ((tempString = bufferreader.readLine()) != null) {
script.append(tempString).append("\n");
}
bufferreader.close();
filereader.close();
return script.toString();
}
}
网友评论