Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我会得到额外的字符'^@';在Java中使用byteBuffer将字符写入大文件时_Java_File_Io_Character_Filewriter - Fatal编程技术网

为什么我会得到额外的字符'^@';在Java中使用byteBuffer将字符写入大文件时

为什么我会得到额外的字符'^@';在Java中使用byteBuffer将字符写入大文件时,java,file,io,character,filewriter,Java,File,Io,Character,Filewriter,我试图将字符写入文件,但不确定它为什么写入^@ ^@1^@:^@1^@ ^@2^@ ^@3^@ ^@3^@0^@4^@ 这是预期产出 1:1 2 3 3 0 4 有趣的是,对于较小的文件输出(当它大约有几百行长时),我没有这种奇怪的行为 但是,当输出为100000多行时,只有我注意到这种奇怪的行为 这是我的代码片段 final static int charByteSize= 2; // 1 char =2 bytes writeTofile(FileChannel fc, ResultC

我试图将字符写入文件,但不确定它为什么写入
^@

^@1^@:^@1^@ ^@2^@ ^@3^@ ^@3^@0^@4^@
这是预期产出

1:1 2 3 3 0 4
有趣的是,对于较小的文件输出(当它大约有几百行长时),我没有这种奇怪的行为

但是,当输出为100000多行时,只有我注意到这种奇怪的行为

这是我的代码片段

final static int charByteSize= 2; // 1 char =2 bytes

writeTofile(FileChannel fc, ResultClass result) throws IOException {

        int key= result.getKey();
        List<Integer> values= result.getValues();
           StringBuilder sb=new StringBuilder();        
        sb.append(key+":");
        for(int value:values)
        {
            sb.append(value+" "); // space delimited value list
        }

        String stringToWrite=sb.toString().trim()+"\n"; //add newline char in end
        char[] arrToWrite=stringToWrite.toCharArray();

        ByteBuffer buf = ByteBuffer.allocate(arrToWrite.length*charByteSize);

        for(char theChar: arrToWrite)
        {
            buf.putChar(theChar);
        }

        buf.flip();     
        fc.write(buf);

} 
不,不是!这是真的;但在其他方面,这是错误的。在Java中,
char
只是字符的基本存储单元;更准确地说,它是一个UTF-16代码单元。请注意,补充Unicode字符(U+10000及以上)需要两个字符

文件中存储的不是字符,而是字节。这意味着您首先需要将字符串编码为字节数组;例如:

final byte[] array = theString.getBytes("UTF-8");

然后将这些字节写入输出文件。

+1,谢谢。今天我学到了一件新东西。因为你说2个字节用来存储字符,所以当我想一次一个字符地读回同一个文件时,我可以安全地将2个字节分配给byteBuffer来读取,否则也会出错?好的,我真正的意思是,在存储方面,字符是16位,字节是8位;对不起,你弄糊涂了。为了读回文本,你也不能说什么就做什么。您需要将字节流解码为字符流。例如,通过将包含字节的输入流包装到
InputStreamReader
,不要忘记指定要使用的字符编码(
Charset
)!
// 1 char =2 bytes
final byte[] array = theString.getBytes("UTF-8");