简体   繁体   中英

How to write in file by BufferedOutputStream?

I want to copy data from demo1.txt to demo2.txt , although I can do it by BufferedReader , I want to copy by BufferedInputStream / BufferedOutputStream . Please show me how to do this.

import java.io.*;
class stream4
{
    public static void main(String arr[])
    {
        BufferedInputStream bfis=new BufferedInputStream(new FileInputStream("demo1.txt"));
        BufferedOutputSteam bfos=new BufferedOutputStream(new FileOutputStream("demo2.txt"));
        byte b[]=(bfis.read());
        bfos.write(b);
        bfis.close();
        bfos.close();
    }
}

change

byte b[]=(bfis.read());

to

    byte[] b = new byte[1024];
    try {
        for (int readNum; (readNum = bfis.read(b)) != -1;) {
            bfos.write(b, 0, readNum);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    finally {
        bfis.close();
        bfos.close();
    }

as bfis.read() the next byte of data, or -1 if the end of the stream is reached.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Main
{
    public static void main(String[] args) throws Exception
    {
       String fromFileName = "demo1.txt";
       String toFileName = "demo2.txt";
       BufferedInputStream in = new BufferedInputStream(new FileInputStream(fromFileName));
       BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(toFileName));
       byte[] buff = new byte[32 * 1024]; 
       int len = 0;
       while ((len = in.read(buff)) > 0) //If necessary readLine()
         out.write(buff, 0, len);
       in.close();
       out.close();
     }
}

This will do the job :). Just specify what kind of byte size you are looking at, and from there use a loop to continue to read the file.

As others correctly suggested you need your own buffer actually to read and write by portions, which is represented as byte array of the specified size. So this now make no sense in wrapping your FileInputStream and FileOutputStream with BufferedInputStream and BufferedOutputStream - they are useful if you input from stream and output by smaller portions. I suggest just making your buffer bigger than suggested (say, 16384 or 32768) and remove unnecessary BufferedInputStream and BufferedOutputStream in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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