将波斯语或其他非英语语言的字符串读写到文本文件中的Java操作

4

我想要一个Java.io包或其他可用包中的任何类的代码,以读取和写入像“سلام به همه دوستانم”(波斯语)这样的字符串。但我找不到一个好的方法来实现它。问题在于保存到文件时:在像记事本这样的程序中显示?。谢谢大家。以下是我尝试过的代码:

public static int saveInputToFile(String filelocation) throws IOException
{
    // it will save from console to file;

    // temp data
    // int buffersize = 1;
    // char[] buffer = new char[buffersize];
    //
    // create open file, save userInput(an string) into the file

    // create file:
    File file = new File(filelocation);// to position: file exist, then
                                        // opens, file not exist then
                                        // created and opens
    // read one line data
    InputStreamReader reader = new InputStreamReader(System.in, "UTF-8");
    BufferedReader bufReader = new BufferedReader(reader);
    String userInputLine = bufReader.readLine();
    //
    // write one line data to the file
    OutputStream out = new FileOutputStream(file);
    OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
    writer.write(userInputLine);
    writer.flush();
    writer.close();
    // goal achieved data has been saved to file.
    return 0;

}

public static int saveInputToFileVer2(String filelocation)
        throws FileNotFoundException, UnsupportedEncodingException
{
    // OutputStream outSTream = new FileOutputStream(filelocation);
    PrintWriter writer = new PrintWriter(filelocation, "UTF-8");
    //
    String data = "";
    Scanner scan = new Scanner(System.in, "UTF-8");

    LOOP: while (true) {
        System.out.println("please enter your data to save:");
        data += scan.nextLine();
        System.out.println("do you want to append other data? yes:y no:n");
        char choice = scan.nextLine().charAt(0);
        if (choice == 'y') {
            continue;
        } else {// choise = 'n'
            break LOOP;
        }
    }

    writer.println(data);
    writer.flush();
    writer.close();
    System.out.println("write ended successfully");
    // end
    return 0;
}

1
new InputStreamReader(System.in, "UTF-8"); 你确定 System.in 是使用 UTF-8 编码的吗? - Pshemo
1
如果你正在使用Windows并在控制台上运行应用程序,请检查其代码页。您可以使用chcp命令。对于我来说,它返回852,因此当我从System.in读取时,适当的编码为代码页cp852 - Pshemo
2个回答

2
从流中删除“UTF-8”,并将其放入要写入文件的字符串中。
注意使用阿拉伯或波斯字符书写英语会导致冲突
   InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader bufReader = new BufferedReader(reader);
    String userInputLine = bufReader.readLine();
    //
    // write one line data to the file
    OutputStream out = new FileOutputStream(file);
    OutputStreamWriter writer = new OutputStreamWriter(out);
    writer.write(new String(userInputLine.getBytes("UTF-8")));
    writer.flush();

0

1-诀窍是以阿拉伯语存储并用波斯语显示

将文本从阿拉伯语更改为波斯语

text.trim().replaceAll("ی", "ي").replaceAll("ک", "ك");

将来自波斯语的文本更改为阿拉伯语

text.trim().replaceAll("ي", "ی").replaceAll("ك","ک");

第二种方法是将其存储为base64格式并存储它


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接