开发者

How to save string with code page 1250 into RandomAccessFile in java

开发者 https://www.devze.com 2023-03-09 04:44 出处:网络
I have text file with string wh开发者_如何学Pythonich code page is 1250. I want to save text into RandomAccessFile. When I read bytes from RandomAccessFile I get string with different character. Some

I have text file with string wh开发者_如何学Pythonich code page is 1250. I want to save text into RandomAccessFile. When I read bytes from RandomAccessFile I get string with different character. Some solution...


If you're using writeUTF() then you should read its JavaDoc to learn that it always writes modified UTF-8.

If you want to use another encoding, then you'll have to "manually" do the encoding and somehow store the length of the byte[] as well.

For example:

RandomAccessFile raf = ...;
String writeThis = ...;
byte[] cp1250Data = writeThis.getBytes("cp1250");
raf.writeInt(cp1250Data.length);
raf.write(cp1250Data);

Reading would work similarly:

RandomAccessFile raf = ...;
int length = raf.readInt();
byte[] cp1250Data = new byte[length];
raf.readFully(cp1250Data);
String string = new String(cp1250Data, "cp1250");


This code will write and read a string using the 1250 code page. Of course, you will need to clean it, check exceptions and close streams properly before putting in prod :)

    public static void main(String[] args) throws Exception {
    File file = new File("/toto.txt");
    String myString="This is a test";
    OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("windows-1250"));
    w.write(myString);
    w.flush();
    CharBuffer b = CharBuffer.allocate((int)file.length());
    new InputStreamReader(new FileInputStream(file), Charset.forName("windows-1250")).read(b);
    System.out.println(b.toString());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消