2015-09-13 42 views
0

我有類調用perl腳本:如何在jar文件中調用perl腳本?

Runtime.getRuntime().exec(perlscript.pl) 

類和腳本放在同一個JAR檔案。這個jar是由maven構建的。並且Perl腳本被放置在jar的根目錄下,但該類不在根路徑中。

當我啓動Perl腳本,我得到錯誤:「系統找不到指定文件」

應該在哪裏我把腳本正確調用它?

回答

0

您可以訪問你的腳本像流:

Thread.currentThread().getContextClassLoader().getResourceAsStream("script.pl"); 

如果你的腳本是不是在classpath的根部,利用斜線指向它喜歡:

「路徑/到/腳本/script.pl「

0

這既可以在Eclipse中使用,也可以作爲Maven構建的jar。按照SO answer的說法,我所做的是(i)在jar中找到原始腳本,(ii)將其內容複製到臨時文件夾中新創建的文件中,最後(iii) - 執行該腳本:

// find the original script within the JAR, 
// mine sits in /src/main/resources/Perl/Hello.pl 
InputStream in = PerlCaller.class.getClass().getResourceAsStream("/Perl/Hello.pl"); 
// if the file in the jar's root 
// InputStream in = PerlCaller.class.getClass().getResourceAsStream("/Hello.pl"); 
if (null == in) { 
    System.err.println("Resource ws not found, exiting..."); 
    System.exit(10); 
} 

// copy its content into a temporary file, I use strings since it's a script 
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
File scriptFile = File.createTempFile("perlscript", ".pl"); 
BufferedWriter bw = new BufferedWriter(new FileWriter(scriptFile)); 
String line; 
while ((line = reader.readLine()) != null) { 
    bw.write(line + "\n"); 
} 
bw.close(); 

// execute the newly created file 
String[] command = { "perl", scriptFile.getAbsolutePath() }; 

final ProcessBuilder pb = new ProcessBuilder(command); 
pb.redirectErrorStream(true); 
final Process p = pb.start(); 

BufferedReader outputReader = new BufferedReader(new InputStreamReader(p.getInputStream())); 
StringBuilder builder = new StringBuilder(); 
String outputLine = null; 
while ((outputLine = outputReader.readLine()) != null) { 
    builder.append(outputLine); 
    builder.append(System.getProperty("line.separator")); 
} 
String scriptOutput = builder.toString(); 

System.out.println(scriptOutput); 

希望這有助於!