我想要一个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;
}
new InputStreamReader(System.in, "UTF-8");
你确定System.in
是使用UTF-8
编码的吗? - Pshemochcp
命令。对于我来说,它返回852
,因此当我从System.in
读取时,适当的编码为代码页cp852
。 - Pshemo