gpt4 book ai didi

java - 从 python 调用 Java 应用程序时无法读取文件

转载 作者:行者123 更新时间:2023-11-30 10:05:46 24 4
gpt4 key购买 nike

我有一个 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,不确定这是否有任何区别。

最佳答案

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

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

关于java - 从 python 调用 Java 应用程序时无法读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55077479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com