[英]is there a way to set encoding when writing with RandomAccessFile
I open a text file using windows-1251 encoding 我使用Windows-1251编码打开文本文件
FileInputStream is = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"windows-1251"));
and later write the changes like: 然后写如下更改:
RandomAccessFile file = new RandomAccessFile(new File(path), "rw");
try {
file.write(etMainView.getText().toString().getBytes());
file.close();
Toast.makeText(this, "Changes saved", Toast.LENGTH_SHORT)
.show();
//..... Exception handling
The problem is that it messes up all the non-latin letters in the file and when I open it again, all such letters are replaced with some unreadable characters. 问题是它弄乱了文件中的所有非拉丁字母,当我再次打开它时,所有这样的字母都被替换为一些不可读的字符。 I guess the
RandomAccessFile
uses UTF-8 by default which is causing troubles. 我猜默认情况下
RandomAccessFile
使用UTF-8会引起麻烦。 How can I save the file keeping the encoding I used to open it? 如何保存文件以保持打开时的编码?
Use .getBytes("windows-1251")
instead of .getBytes()
; 使用
.getBytes("windows-1251")
代替.getBytes()
; .getBytes()
uses the default JVM encoding. .getBytes()
使用默认的JVM编码。
If you want to use the stream apis you can do it this way 如果您想使用流api,可以通过这种方式进行
RandomAccessFile file = ....;
FileChannel fc = file.getChannel();
OutputStream os = Channels.newOutputStream(fc);
OutputStreamWriter osw = new OutputStreamWriter(os, "windows-1251");
osw.write("Some sring");
osw.flush();
file.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.