文档详情

Java中正确使用RandomAccessFile向文件中写入中文.docx

发布:2017-12-15约5.37千字共4页下载文档
文本预览下载声明
使用RandomAccessFile向数据库写入中文的时候, *使用write(String.getBytes()), 能够正常写入 *使用writeBytes(String), writeChars(String), writeUTF(String)均产生乱码。如果我对您的问题理解正确的话,经过分析,我认为如果您是使用RandomAccessFile来访问数据库的话,为了正确写入中文,您最好使用write(String.getBytes())的方式。这主要有如下两方面的原因: 1、当java运行时,实际上存在两种字符编码方式。nativecode编码和unicode编码。 * 文件被操作系统保存时,都是以nativecode的编码方式保存的。这也是我们有时候在浏览器或电子邮件客户端软件中看到乱码后,改变浏览器或电子邮件客户端软件的编码设置(例如:GB2312,GB18030或者是BIG5)就可以正确的显示。 * 在JAVA程序内部,字符串都是以UNICODE的方式来表示的。 Java的内核是unicode的,其class文件也是这样的。另外在java代码中,string中的char是用unicode编码方式来表示的,string的bytes是用相应的nativecode编码方式来表示的。 由于RandomAccessFile是同native file来打交道,所以必然存在一个nativecode和unicode的转化过程。 2、RandomAccessFile的文件写入方式。在RandomAccessFile的Javadoc中,对于各种文件写入方式有不同的定义。 * public void write(byte[] b):Writes b.length bytes from the specified byte array to this file, starting at the current file pointer. * public final void writeBytes(String s) throws IOException Writes the string to the file as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits. The write starts at the current position of the file pointer.(请注意每个字符的高8位都会被抛弃掉。) * public final void writeChar(int v) throws IOException Writes a char to the file as a two-byte value, high byte first. The write starts at the current position of the file pointer.(采用的是Big-endian的存储方式,注意由于x86架构的限制,Windows默认采用Little-endian) * public final void writeChars(String s) throws IOException Writes a string to the file as a sequence of characters. Each character is written to the data output stream as if by the writeChar method. The write starts at the current position of the file pointer.(注意writeChars采用的是writeChar的写入方式。)* public final void writeUTF(String str) throws IOException Writes a string to the file using modified UTF-8 encoding in a machine-independent manner. First, two bytes are written to the file, starting at the current file pointer, as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually w
显示全部
相似文档