overexchange
overexchange

Reputation: 1

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.

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

Upvotes: 0

Views: 88

Answers (2)

fge
fge

Reputation: 121760

[...]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.

Sample code with 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);
}

Upvotes: 4

Sumedh
Sumedh

Reputation: 404

You are using default constructor for FileOutputStream Try using this:

out = new FileOutputStream(fileStr,true);

So that now your data will be appended instead of being overwritten.You can go through this: doc

Upvotes: 0

Related Questions