简体   繁体   中英

is there a way to set encoding when writing with RandomAccessFile

I open a text file using windows-1251 encoding

            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. How can I save the file keeping the encoding I used to open it?

Use .getBytes("windows-1251") instead of .getBytes() ; .getBytes() uses the default JVM encoding.

If you want to use the stream apis you can do it this way

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM