使用scanner逐行读写文件,新生成的文件比源文件小,这是为何?
附上源码 // 逐行读取大文档
public void changelog() throws Exception {
FileInputStream inputStream = new FileInputStream(sourcePath);
FileOutputStream outputStream = new FileOutputStream(destinationPath);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
Scanner sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
bw.write(line);
bw.write("\n");
}
if (inputStream != null)
inputStream.close();
if (sc != null)
sc.close();
bw.flush();
bw.close();
outputStream.close();
System.out.println(1);
}

解决方案 »

  1.   

    源文档换行是 \r\n 结尾,目标文档你只写了 \n 换行
      

  2.   

    你没有按照字节复制,出现了差异最好按照这样            fis = new FileInputStream(str);
     
                fos = new FileOutputStream(strs);
                byte[] buf = new byte[1024 * 1024];
                int len;
                while ((len = fis.read(buf)) != -1) {
                    fos.write(buf, 0, len);
     
                }