以下代码在我的本地PC中具有I / O权限并正确运行。但是,当我试图在我的Windows server2012上执行此操作时,出现了一些问题。它不能通过使用exec正确运行python代码,我的python无法给出最终结果。我认为它没有I / O的权限,但为什么呢?
Java代码:
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class test {
private static void generateFile() throws IOException{
BufferedWriter bw = new BufferedWriter(new FileWriter("src/test/input.txt", false));
String eventString = "This is a example";
bw.write(eventString);
bw.close();
}
private static void getFile() throws IOException{
BufferedReader br = new BufferedReader(new FileReader("src/test/output.txt"));
String jsonResults = br.readLine();
br.close();
}
public static void main(String[] args) throws IOException {
generateFile();
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("python test.py", null, new File("src/test/"));
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
try {
pr.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
pr.destroy();
}
getFile();
}
}
python代码:
f = open('input.txt', 'r')
line = f.readline()
with open('output.txt', 'w') as fw:
fw.write(line)
print("Done!")
错误信息:
Exception in thread "main" java.io.FileNotFoundException: src\test\output.txt (The system cannot find the specified file.)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at test.test.getFile(test.java:21)
at test.test.main(test.java:49)
答案 0 :(得分:0)
这里有各种各样的东西(暂时更多&#34;代码质量&#34;提示):
个人&#34;部分&#34;,如下所示 - 都应该采用简单的辅助方法:
String eventString = getJsonEventListInTopic(topicLabel);
FileWriter fw = ...
fw.close();