也谈字符流和字节流

来源:互联网 发布:深圳云知空间有限公司 编辑:程序博客网 时间:2024/04/29 16:53

之前对一些文件用字符流的方式去读取,结果转回String的时候没太注意,发生了一些异常,很诡异。做一次记录。

//读取文件内容try {FileInputStream fs  = new  FileInputStream(file);byte[] buf = new byte[(int)file.length()];fs.read(buf);FileReader fr = new FileReader(file);char[] buf1 = new char[(int)file.length()];int i = fr.read(buf1);System.out.println(new String(buf).equals(String.valueOf(buf1, 0, i)));//trueSystem.out.println(new String(buf).equals(String.valueOf(buf1)));//false} catch (IOException e) {e.printStackTrace();}

造成这个差异的主要原因在于char[]数组默认存的是'\0',如果数组长度过长,转换string的时候末尾'\0'并没有被略去。会有一些异样。

0 0
原创粉丝点击