Django调用java时,为什么utf8字符输出不正常?

2024-04-19 16:18:36 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用django时,我编写了一个可以由http://myhost/XXX/testIndex调用的方法

def testIndex(request):
    res = os.system('java -jar test.HelloWorld' > /tmp/log)
    ... ...

HelloWorld java如下所示:

    public class HelloWorld {
    public static void main(String[] args) throws IOException {
        System.out.println("hello!");
        System.out.println("你好!");
}

当我访问http://myhost/XXX/testIndex时,结果是当我打开/tmp/log文件时,UTF-8字符不正确! 像这样

hello! ??!

发生什么事了?顺便说一句,我在linux centOS下


Tags: django方法loghttphellojavapublicout
1条回答
网友
1楼 · 发布于 2024-04-19 16:18:36

你有两个问题:

  1. 您已经在Java源代码中输入了非ASCII字符。这通常不被认为是好的实践,因为您需要告诉Java编译器您对源文件使用了什么编码。如果是UTF-8,请尝试:javac -encoding UTF-8 HelloWorld.java

  2. 的默认编码系统输出可能不是UTF-8。如果您说出您使用的是哪个JRE,会有所帮助,因为不同的实现的行为可能略有不同。您可以使用java -Dfile.encoding=UTF-8显式指定编码,尽管这也是not recommended。如果是Sun或openjdkjre,则需要在Java启动之前设置LANG环境变量;您可以在web服务器配置中这样做,或者使用subprocesspython模块来指定传递给新进程的环境。

相关问题 更多 >