我使用PhantomJS对网站进行无头测试。由于exe
将捆绑在jar
文件中,我决定将其读取并将其写入临时文件,以便我可以通过绝对路径正常访问它。
以下代码,用于将InputStream
转换为引用新临时文件的String
:
public String getFilePath(InputStream inputStream, String fileName)
throws IOException
{
String fileContents = readFileToString(inputStream);
File file = createTemporaryFile(fileName);
String filePath = file.getAbsolutePath();
writeStringToFile(fileContents, filePath);
return file.getAbsolutePath();
}
private void writeStringToFile(String text, String filePath)
throws FileNotFoundException
{
PrintWriter fileWriter = new PrintWriter(filePath);
fileWriter.print(text);
fileWriter.close();
}
private File createTemporaryFile(String fileName)
{
String tempoaryFileDirectory = System.getProperty("java.io.tmpdir");
File temporaryFile = new File(tempoaryFileDirectory + File.separator
+ fileName);
return temporaryFile;
}
private String readFileToString(InputStream inputStream)
throws UnsupportedEncodingException, IOException
{
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null)
{
inputStringBuilder.append(line);
inputStringBuilder.append(System.lineSeparator());
}
String fileContents = inputStringBuilder.toString();
return fileContents;
}
这样可行,但是当我尝试启动PhantomJS时,它会给我一个ExecuteException
:
SERVERE: org.apache.commons.exec.ExecuteException: Execution failed (Exit value: -559038737. Caused by java.io.IOException: Cannot run program "C:\Users\%USERPROFILE%\AppData\Local\Temp\phantomjs.exe" (in directory "."): CreateProcess error=216, the version of %1 is not compatible with this Windows version. Check the system information of your computer and talk to the distributor of this software)
如果我没有尝试从PhantomJS
中读取jar
因此使用相对路径,则可以正常工作。问题是我如何从jar文件中读取和执行PhantomJS
,或至少通过阅读和编写新的(临时)文件来解决问题。
答案 0 :(得分:3)
您无法执行JAR条目,因为JAR是zip文件,操作系统不支持从zip文件中运行可执行文件。它们原则上可以,但它可以归结为“将exe复制出拉链然后运行它”。
exe正在被破坏,因为你将它存储在String中。字符串不是二进制数据,它们是UTF-16,这就是为什么你不能直接从InputStream读取字符串 - 需要编码转换。您的代码正在以UTF-8的形式读取exe,将其转换为UTF-16,然后使用默认字符集将其写回。即使您的计算机上的默认字符集恰好是UTF-8,这也会导致数据损坏,因为exe文件无效UTF-8。
尝试使用此尺寸。 Java 7引入了NIO.2,其中包括许多常用文件操作的便捷方法。包括将InputStream放入文件中!我也在使用临时文件API,如果你的应用程序的多个实例同时运行,它将防止冲突。
public String getFilePath(InputStream inputStream, String prefix, String suffix)
throws IOException
{
java.nio.file.Path p = java.nio.file.Files.createTempFile(prefix, suffix);
p.toFile().deleteOnExit();
java.nio.file.Files.copy(inputStream, p, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
return p.toAbsolutePath().toString();
}