【问题标题】:Unable to read file when Java application is invoked from python从python调用Java应用程序时无法读取文件
【发布时间】:2019-07-31 07:52:31
【问题描述】:

我有一个 Java 程序,读取一个文件(其中包含来自本地语言的字符),并填充一个字符串。当程序直接运行时,它工作正常。

但是当从 Python 调用相同的程序时,它无法填充字符串。

        public static void main(String[] args) {
        File inputFile = new File("input.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile),"UTF-8"));
      string output = "";
        while ((line = br.readLine()) != null) {
           // This block never hits when invoked by python. It works fine when java program runs directly.
           output +=line+" ";
         }
         ...
         }

我从 Python 调用它如下

cmd = ['java', java_class]
subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

任何输入?顺便说一句,我正在使用 Atom IDE,不确定这是否有什么不同。

【问题讨论】:

  • 您遇到的错误是什么?
  • 没有错误。只是我的输出为空而不是文件内容
  • @TheRoy,感谢分享链接。但不确定这个链接是否有帮助,它只是告诉如何在 python 中读取 java 程序的输出。我能够从 python 调用 java 应用程序。问题是当从 python 调用 java 应用程序时,它无法读取文件的内容,当 java 应用程序直接运行时,文件内容是完全可读的。

标签: java python python-3.x


【解决方案1】:

我试过你的例子,它对我有用。让我们看看它是否适合你。然后我会回复你我对这个问题的看法。

import java.io.*;


public class Python2JavaMessaging {
        public static void main(String[] args) {
                try {
                        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
                        PrintWriter writer = new PrintWriter("result.txt", "UTF-8");
                        String s = bufferRead.readLine();
                        while(s.equals("x")==false) {
                                writer.println(s);
                                s = bufferRead.readLine();
                        }
                        writer.close();
                } catch(IOException e) {
                        e.printStackTrace();
                }
        }
}

Python脚本如下:

#!/usr/bin/python

import subprocess

cmd = ['java', '-classpath', '.' , 'Python2JavaMessaging']
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding='utf8')

p.stdin.write("First line\r\n")
p.stdin.write("Second line\r\n")
p.stdin.write("x\r\n") # this line will not be printed into the file

【讨论】:

  • 顺便说一句,我用stdin写的。我们也可以将其更改为文件。在你的情况下, input.txt
  • 你能帮我提供一个文件样本吗?此外,如果我的文件内容是英文,那么再次强调一下,一切正常。只有当我有某种母语的文件内容时,它才起作用。
  • 您需要为此使用正确的编码。我在示例中使用了编码。尝试您的母语特定编码。
  • 查看这篇文章以写入文件。 stackoverflow.com/questions/15535240/…
  • 如果您认为您的查询已通过这些解决,那么请接受答案以关闭线程。
猜你喜欢
  • 2013-05-25
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2018-07-03
  • 1970-01-01
相关资源
最近更新 更多