FileInputStream fis = new FileInputStream(new File("C:\\文件1.txt"));
FileOutputStream fos = new FileOutputStream(new File("C:\\文件2.txt"));int i=0;
byte[] buffer = new byte[2];
while ((i = fis.read(buffer)) > 0) {
fos.write(buffer, 0, i);
}fis.close();
fos.close();
“文件1.txt”有1M, 这里我故意将buffer = new byte[2]。
fos.write(buffer, 0, i) 是不是就是说每次将byte[2]的内容写入到“文件2.txt”中?
还请问一下fos.write(buffer, 0, i)中第2个参数0,是什么意思?第2个参数可以是0吗?如果第2个参数总是为0,是不是就会把前面写入的内容覆盖了呢?
api上说的偏移量到底指的什么意思?
write(byte[])和write(byte[],off,len)到底有何区别,那个好一点呢?请不要复制api上的内容过来!
FileOutputStream fos = new FileOutputStream(new File("C:\\文件2.txt"));int i=0;
byte[] buffer = new byte[2];
while ((i = fis.read(buffer)) > 0) {
fos.write(buffer, 0, i);
}fis.close();
fos.close();
“文件1.txt”有1M, 这里我故意将buffer = new byte[2]。
fos.write(buffer, 0, i) 是不是就是说每次将byte[2]的内容写入到“文件2.txt”中?
还请问一下fos.write(buffer, 0, i)中第2个参数0,是什么意思?第2个参数可以是0吗?如果第2个参数总是为0,是不是就会把前面写入的内容覆盖了呢?
api上说的偏移量到底指的什么意思?
write(byte[])和write(byte[],off,len)到底有何区别,那个好一点呢?请不要复制api上的内容过来!
如果第2个参数总是为0,实际你就每次只往文件中写人buffer[0]这个数据
偏移代表的就是每次写入文件的字节数
write(byte[])和write(byte[],off,len)到底有何区别,那个好一点呢?
区别就是write(byte[])每次都把byte数组中的数据写入了文件,write(byte[],off,len)可以定义写入的字节 数,如果按照你程序的写法,也就是每次写入的是读入的字节数
写程序的时候要用write(byte[],off,len)
举个例子文件1存有15字节的数据
FileInputStream fis = new FileInputStream(new File("C:\\文件1.txt"));
FileOutputStream fos = new FileOutputStream(new File("C:\\文件2.txt"));int i=0;
byte[] buffer = new byte[10];
while ((i = fis.read(buffer)) > 0) {
fos.write(buffer );
}fis.close();
fos.close();
循环到第二次的时候,实际读入的是5个字节的数据,但是往文件而写的时候,却写入了10个字节的数据
这样就会出问题
顺便说下,如果读的是中文数据的话,用这种读写方式很如意出现乱码的
第二参数代表就是重byte数组的第一个元素开始写,如果只是拷贝文件的需要肯定是要从0开始的
FileOutputStream fos = new FileOutputStream(new File("C:\\文件2.txt"));int i=0;
byte[] buffer = new byte[fis.read()];
while ((i = fis.read(buffer)) > 0) {
fos.write(buffer, 0, i);
}fis.close();
fos.close();