java exec运行python程序,而python没有I / O权限

时间:2017-02-21 08:19:51

标签: java python python-2.7 cmd exec

以下代码在我的本地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)

1 个答案:

答案 0 :(得分:0)

这里有各种各样的东西(暂时更多&#34;代码质量&#34;提示):

  • 你糟糕的方法是做太多的事情。例如:

个人&#34;部分&#34;,如下所示 - 都应该采用简单的辅助方法:

String eventString = getJsonEventListInTopic(topicLabel);
FileWriter fw = ...
fw.close();
  • 含义:您想了解Single Layer Of Abstraction principle
  • 核心指出您在实际问题上取得进展:当您在该Windows系统上手动运行您的python脚本时(具有完全相同的参数/参数)命令行 - 这有用吗?你知道,它可能是超级简单的东西,因为&#34; python.exe不在你的路径中#34;