簡體   English   中英

使用RandomAccessFile編寫時,有沒有辦法設置編碼

[英]is there a way to set encoding when writing with RandomAccessFile

我使用Windows-1251編碼打開文本文件

            FileInputStream is = new FileInputStream(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(is,
                "windows-1251"));

然后寫如下更改:

  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

問題是它弄亂了文件中的所有非拉丁字母,當我再次打開它時,所有這樣的字母都被替換為一些不可讀的字符。 我猜默認情況下RandomAccessFile使用UTF-8會引起麻煩。 如何保存文件以保持打開時的編碼?

使用.getBytes("windows-1251")代替.getBytes() ; .getBytes()使用默認的JVM編碼。

如果您想使用流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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM