我正在使用谷歌闭包编译器来格式化我的网络项目中的一些JavaScript文件。因此,我正在编写一个Java应用程序来遍历根目录下的所有js文件。出于测试目的,我只试试一个单独的javascript文件,如下所示:
public static void main(String[] args){
JSBeautifier js = new JSBeautifier();
js.beautify("'C:/CodeScanner/src/test/resources/testJS.js'");
}
public void beautify(String filePath) {
String srcFileArg = "--js " + filePath;
ProcessBuilder pb = new ProcessBuilder("java", "-jar" , "compiler.jar", srcFileArg).inheritIO();
try {
Process p = pb.start();
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while(br.readLine() != null){
System.out.println(br.readLine());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
然而,当它被执行时,它给出了例外:
Exception in thread "main" java.nio.file.InvalidPathException: Illegal char <:> at index 7: --js 'C:/CodeScanner/src/test/resources/testJS.js'
at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
at java.nio.file.Paths.get(Paths.java:84)
at com.google.javascript.jscomp.CommandLineRunner.findJsFiles(CommandLineRunner.java:1753)
at com.google.javascript.jscomp.CommandLineRunner.findJsFiles(CommandLineRunner.java:1730)
at com.google.javascript.jscomp.CommandLineRunner$Flags.getJsFiles(CommandLineRunner.java:928)
at com.google.javascript.jscomp.CommandLineRunner.initConfigFromFlags(CommandLineRunner.java:1325)
at com.google.javascript.jscomp.CommandLineRunner.<init>(CommandLineRunner.java:1176)
at com.google.javascript.jscomp.CommandLineRunner.main(CommandLineRunner.java:1834)
在命令行中,可以成功执行此操作(java -jar compiler.jar --js&#39; C:/CodeScanner/src/test/resources/testJS.js')。
任何人都可以伸出援手吗?
答案 0 :(得分:2)
看起来ProcessBuilder正在尝试执行:
java "-jar" "compiler.jar" "--js 'C:/CodeScanner/src/test/resources/testJS.js'"
这导致js编译器看到:
argv[0] = "--js 'C:/CodeScanner/src/test/resources/testJS.js'"
而不是:
argv[0] = "--js"
argv[1] = "'C:/CodeScanner/src/test/resources/testJS.js'"
要纠正这个问题,我会尝试更改:
String srcFileArg = "--js " + filePath;
ProcessBuilder pb = new ProcessBuilder("java", "-jar" , "compiler.jar", srcFileArg).inheritIO();
到
String srcFileArg = filePath;
ProcessBuilder pb = new ProcessBuilder("java", "-jar" , "compiler.jar", "--js", srcFileArg).inheritIO();