-3

要用不同的语言登录服务器说“عاتبوها.txt”,但它在服务器上显示“?????.txt”。

在服务器上写入日志文件的代码如下:

BufferedWriter bw = null;
FileWriter fw = null;
String label = "label test";

// this content comming dynamic value from another method.
String content = "هذا هو اختبار عينة يرجى اختبار"; 
// this content comming dynamic value from another method.
String room    = "اختبار"; 


Date date = new Date();
         try {
                String dt = sdf.format(date);
                //String convertedRoom = new String(room.getBytes("UTF-8"));
                String fileName = room.concat("_").concat(dt).concat(".txt");
                File f = new File(fileName);
                if(!f.exists()) {
                    f.createNewFile();
                    f.setWritable(true);
                }
                fw = new FileWriter(fileName,true);
                bw = new BufferedWriter(fw);

                bw.write(content);

                bw.flush();
            } catch (IOException e) {
                //e.printStackTrace();
            } finally {
                try {
                    if (bw != null)
                        bw.close();
                    if (fw != null)
                        fw.close();
                } catch (IOException ex) {
                    //ex.printStackTrace();
                }
            }

现在日志生成在服务器上正常,日志文件上的数据在文件中也正常......但问题是文件名不是用另一种语言(如 arebic.txt)生成的,它显示 ?????????? _.txt...请帮忙。

4

1 回答 1

0

首先是一个小问题,必须以与 java 编译器编译相同的编码(字符集)编辑 java 源代码,以便正确翻译 java 源代码中的阿拉伯文本。这可以通过将阿拉伯语中的字符串文字与带有 u-escaped Arabic: 的字符串文字进行比较来测试"\u....\u...."

这里有两个问题:文件名和文件内容。对于文件名,请检查上述小问题。如果这没有帮助,您可能需要在 UTF-8语言环境中运行应用程序服务器;查看Linux帮助。

在 Windows 下,文件名确实不适用于我的位置。您可以编写一个带有拉丁字符的zip文件,并在其中包含 UTF-8 文件名。

必须使用转换写入文件内容,以便生成的字节为 UTF-8(或阿拉伯语 Windows-1256)。此处 FileWriter/FileReader 不可用,因为它们使用默认编码,并且无法像其他类一样指定编码。

    String room = "اختبار";
    System.out.println("room = " + uescape(room));
    room =  "\u0627\u062e\u062a\u0628\u0627\u0631";

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    String dt = sdf.format(date);
    String fileName = room + "_" + dt + ".txt";
    Path f = Paths.get(fileName);
    try (BufferedWriter bw = Files.newBufferedWriter(f, StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {

        bw.write("\r\n=s=" + label + "====" + date.toString() + "====>");
        bw.write(content);
        bw.write("=e=" + date.toString() + "===>\r\n");
    } catch (IOException e) {
        // FIXME Do something with the exception...
    }
}

private static String uescape(String room) {
    StringBuilder sb = new StringBuilder();
    sb.append('\"');
    for (char ch : room.toCharArray()) {
        if (32 <= ch && ch < 127) {
            sb.append(ch);
        } else {
            sb.append(String.format("\\u%04x", 0xFFFF & ch));
        }
    }
    sb.append('\"');
    return sb.toString();
}

顺便说一句,如果文本适用于 Windows,请使用\r\n(CR-LF) 而不是\n(LF)。

于 2017-09-20T09:34:39.250 回答