字节输入流需要准备一个缓存字节数组byte[]1
- 提高效率,因为一次默认read();方法只会读一个字节byte,使用1024位的数组以后read(byteObject);可以一次性读1024个字节
在读字节和写字节的循环体while内末尾需要添加清空缓存字节数组的方法,可以是for循环赋值或者使用Arrays.fill(byteObject,(byte)0);
把所有空位写成0- 输出文档会比原文档多内容的代码(末尾多很多00)
package Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
public class FileInputTest {
public static void main(String[] args) {
File xml=new File("/home/your/config.yml");
FileInputStream input=null;
try {
input=new FileInputStream(xml);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] cache=new byte[2048];
try {
while(input.read(cache)!=-1) {
String s=new String(cache);
System.out.println(s);
Arrays.fill(cache, (byte)0);
System.out.println(new Date()); //通过日期简单判断文档被读取了几次
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 改进代码
package Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputTest {
public static void main(String[] args) {
File xml=new File("/home/your/config.yml");
File xmlOut=new File("/home/your/configOut.yml");
FileInputStream input=null;
FileOutputStream output=null;
try {
input=new FileInputStream(xml);
output=new FileOutputStream(xmlOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] cache=new byte[2048];
int hasRead=0;
try {
hasRead=input.read(cache);
while(hasRead!=-1) {
String s=new String(cache); //准备输出到控制台的字符串
System.out.println(s); //输出到控制台作为提示
output.write(cache,0,hasRead);
hasRead=input.read(cache);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
数组大小一般在1024-8*1024(1kb-8kb),试验过缓存空间在一定范围以内越大传输效率越高,但是过小/过大都会降低效率。 ↩︎
自己定义的缓存字节数组如
byte[2048]
↩︎数组起点,即0 ↩︎
写入终点,
read();
方法的返回值 ↩︎flush方法是字节输出流的抽象父类OutputStream的方法,所以每个字节输出流类都会有flush方法。但是有些没有缓冲区的类flush方法只是被重写了,但什么都不做,也就是方法体是为空的。所以FileOutputStream调用flush方法什么都没做。另外,close方法也会强制清空缓冲区,因此不写flush也是可以的,但对于不能马上调用close方法的,还是需要用flush方法强制清空一下。毕竟一旦调用close方法,这个流对象也就不能用了。 ↩︎