简体   繁体   English

查询Java I / O字节流类

[英]Query on java I/O byte stream class

Below is the program which created separate byte streams for reading from and writing into same file. 以下是创建用于读取和写入同一文件的单独字节流的程序。

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();
            }
        }


    }
}

Below is the observation: 以下是观察结果:

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

I know that FileInputStream and FileOutputStream are non-buffer byte stream I/O classes. 我知道FileInputStreamFileOutputStream是非缓冲区字节流I / O类。

I expect that the file size to remain same after writing to same file. 我希望写入相同文件后文件大小保持不变。

What could be under-hood reason that file size goes to zero? 文件大小为零的幕后原因是什么?

Note : am learning java 1.6 I/O 注意:正在学习Java 1.6 I / O

[...]for reading from and writing into same file. 读取和写入同一文件。

NEVER DO THAT. 绝对不要做。 EVER . 永远

The results are unpredictable. 结果是不可预测的。

If you want to modify the contents of a file, write the new contents into a new file and then atomically rename to the old -- after you have ensured that the new content was successfully written. 如果要修改文件的内容,请在确保成功写入新内容之后 ,将新内容写入文件,然后原子重命名为旧文件。

Also, this is 2014, so unless you REALLY have to use Java 6, use java.nio.file instead , especially if you have to rename, since File will leave you stranded more often than not . 而且,这是2014年,因此除非您真的必须使用Java 6,否则请改用java.nio.file ,尤其是在您必须重命名的情况下,因为File会使您经常陷入困境

Sample code with java.nio.file: 带有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);
}

You are using default constructor for FileOutputStream Try using this: 您正在使用FileOutputStream的默认构造函数尝试使用以下方法:

out = new FileOutputStream(fileStr,true);

So that now your data will be appended instead of being overwritten.You can go through this: doc 这样一来,您的数据将被追加而不是被覆盖。您可以执行以下操作: doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM