查询java I / O字节流类

时间:2014-12-21 12:48:42

标签: java io fileinputstream fileoutputstream

下面是创建单独字节流以便读取和写入同一文件的程序。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyNoBuffer{
    public static void main(String[] args){
        FileInputStream in = null;
        FileOutputStream out = null;
        Long startTime, elapsedTime;

        //String inFileStr = "C:\\project\\books\\java-Preparation\\main_docs\\practice.jpg";
        //String outFileStr = "C:\\project\\books\\java-Preparation\\main_docs\\practice_out.jpg";
        String fileStr = "C:\\project\\books\\java-Preparation\\main_docs\\practice.jpg";

        File file = new File(fileStr);
        System.out.println("File size before - r/w is: " + file.length() + " bytes");
        try{
            in = new FileInputStream(fileStr);
            out = new FileOutputStream(fileStr);

            startTime = System.nanoTime();
            int byteRead;

            while((byteRead = in.read()) != -1){
                out.write(byteRead);
            }

            elapsedTime = System.nanoTime() - startTime;
            System.out.println("Elapsed Time is: " + (elapsedTime/1000000.0) + " msec");
            System.out.println("File size after - r/w is: " + file.length() + " bytes");

        }catch(IOException ex){
            ex.printStackTrace();
        }finally{
            try{
                if(in != null){
                    in.close();
                }
                if(out != null){
                    out.close();
                }
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }


    }
}

以下是观察结果:

File size before - r/w is: 1115512 bytes
Elapsed Time is: 0.040711 msec
File size after - r/w is: 0 bytes

我知道FileInputStreamFileOutputStream是非缓冲字节流I / O类。

我希望写入同一文件后文件大小保持不变。

文件大小为零的原因可能是什么?

注意:我正在学习java 1.6 I / O

2 个答案:

答案 0 :(得分:4)

  

[...]用于读取和写入同一文件。

永远不要这样做。 EVER

结果无法预测。

如果要修改文件的内容,请将新内容写入 new 文件,然后以原子方式重命名为旧< - em> 后确保新内容已成功撰写。

此外,这是2014年,所以除非你真的必须使用Java 6,use java.nio.file instead,特别是如果你必须重命名,因为File will leave you stranded more often than not

使用java.nio.file的示例代码:

final Path toChange = Paths.get("pathtoyourfilehere");
final Path dir = toChange.getParent();
final Path tmpfile = Files.createTempFile(dir, "foo", "bar");

try (
    final InputStream in = Files.newInputStream(toChange);
    final InputStream out = Files.newOutputStream(tmpfile);
) {
    // Work with in and out
}

// Then move!
try {
    Files.move(tmpfile, toChange, StandardCopyOption.REPLACE_EXISTING,
        StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException ignored) {
    Files.move(tmpfile, toChange, StandardCopyOption.REPLACE_EXISTING);
}

答案 1 :(得分:0)

您正在使用FileOutputStream的默认构造函数 试试这个:

out = new FileOutputStream(fileStr,true);

现在您的数据将被追加而不是被覆盖。您可以通过以下方式: doc