今天在使用java執行python文件時,因為python文件中輸出的是中文,在Java控制台中全為亂碼。
代碼:
import org.python.util.PythonInterpreter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; /** *@author chenmeiqi *@version 2020年2月26日 下午7:08:24 */ public class test { public static void main(String[] args) throws IOException, InterruptedException { // TODO Auto-generated method stub Process proc = Runtime.getRuntime().exec("D:\\Anaconda3\\envs\\py36\\python.exe D:/spider/ItemCF.py"); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); proc.waitFor(); System.out.println("end"); } }
運行結果:
解決方法:
在讀取python輸出窗口的信息時,只需添加一個參數gbk即可。
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(),"gbk"));
運行結果: