[英]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
. 我想将数据从demo1.txt
复制到demo2.txt
,尽管我可以通过BufferedReader
进行复制,但是我想通过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. 作为bfis.read()
的下一个数据字节;如果到达流的末尾,则为-1。
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. 因此,现在用BufferedInputStream和BufferedOutputStream包装FileInputStream和FileOutputStream是没有意义的-如果您从流中输入并按较小的部分输出,它们将非常有用。 I suggest just making your buffer bigger than suggested (say, 16384 or 32768) and remove unnecessary BufferedInputStream and BufferedOutputStream in this case. 我建议仅使缓冲区大于建议的大小(例如16384或32768),并在这种情况下删除不必要的BufferedInputStream和BufferedOutputStream。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.