字节流和字符流使用非常相似,它们有什么不同喃?
实际上字节流不会用到缓冲区(内存),是文件本身在操作,而字符流会用到缓冲区,通过缓冲区再来操作文件。
例子:
public class OutputStreamDemo7
{
public static void main(String[]
args) throws Exception {
File f= new File("f:" +File.separator +"a.txt" );
OutputStream out= new FileOutputStream(f);
String str= "hello like" ;
byte b[]= str.getBytes();
out.write(b);
//out.close();
}
}
结果在a.txt里面有内容
public class WriterDemo2 {
public static void main(String[]
args) throws Exception{
File f= new File("f:" +File.separator +"a.txt" );
Writer w= new FileWriter(f);
String str= "hello like" ;
w.write(str);
//w.close();
}
}
在a.txt里面没有类容,因为现在内容还在缓冲区中
public class WriterDemo2 {
public static void main(String[]
args) throws Exception{
File f= new File("f:" +File.separator +"a.txt" );
Writer w= new FileWriter(f);
String str= "hello like" ;
w.write(str);
w.flush();
//w.close();
}
}
可以使用flush()强制输出缓冲区的内容,也叫刷新缓冲区
补充:什么叫缓冲区
缓冲区其实就是一段特殊的内存,如果一个程序频繁的访问一个文件,我们就把这个文件先放入缓冲区,加快运行速度
从上面看来,我们使用字节流比字符流好,因为字节流是文件本身在操作,不存在缓冲区的问题(并且所有的文件在硬盘里都是以字节传输的,存储的)
文件的复制
把一个文件的内容复制到另外一个文件
public class OutputStreamDemo8
{
public static void main(String[]
args) throws Exception{
File f= new File("f:" +File.separator +"a.txt" );//源文件
File f1= new File("f:" +File.separator +"b.txt" );
if (!f1.exists()){
f1.createNewFile();
}
InputStream in= new FileInputStream(f);
OutputStream out= new FileOutputStream(f1);
byte b[]= new byte[1024];
int temp=0;
while ((temp=in.read())!=-1){
out.write(temp);
}
out.flush();
in.close();
out.close();
}
}
结果:b.txt里面有了内容
上面的代码没有加判断,自己在写的时候加一些判断。。。