文件输出流:
构造一: File file =newFile("a.txt");
FileOutPutstream out =newFileoutstream(file);
构造二: FileOutPutstream out =newFileoutstream("a.txt");
输出流
FileOutPutstream out =newFileoutstream("a.txt");
out.write(97);
out.write(98);
out.write(99);
out.write(100);
out.write(300);//超过字节范围,就会丢弃多余字节byte[] bytes ={100,101,102,103};
out.write(bytes);//一次写入一个字节数组
out.write(bytes,2,2);//写入字节数组一部分
String str ="好好学习,天天向上";
out.write(str.getbytes);//字符串---字节数组
FileOutPutstream out =newFileoutstream("a.txt");
out.write("你".getbytes());
out.write("\r\n".getbytes());//写入一个换行符//windows:\r\n//LInux:\nI///mac:\r//流使用完之后,必须释放资源
out.close();//close 的用处:童子系统释放关于管理a.txt文件的资源//让I/O流对象变成垃圾,等待垃圾回收器对其回收、
FileOutPutstream out =newFileoutstream("a.txt",true);//true代表追加写入,false不追加
输入流
文件输入流:
构造一: File file =newFile("a.txt");
FileinPutstream in =newFileinputstream(file);//输入流所关联的文件,如果不存在,则报错
构造二: FileinPutstream in =newFileinputstream("a.txt");
int len = in.read();//一次读取一个字节
System.out.println(len);//如果读取不到,则返回-1//创建一个字节数组,充当缓冲区byte[] bytes =newbyte[1024];int len = in.read(bytes);//一次读1024,放缓冲区
System.out.println(len);//len实际读取长度
String s =newstring();
System.out.println(len);//字节数组-----字符串
对文件进行复制
FileOutPutstream out =newFileoutputstream("aa.txt");
FileInputPutstream in =newFileInputstream("a.txt");//循环读写//定义变量int len =0;
while((len=in.read())!=-1){
out.write(len);
out.flush();//刷新}
in.close();
out.close();//由于是一个一个字节循环,影响效率,不建议使用
FileOutPutstream out =newFileoutputstream("aa.txt");
FileInputPutstream in =newFileInputstream("a.txt");//循环读写//定义变量byte[] bytes=newbyte[1024*8];//一次读写一个字节数组int len =0;
while((len=in.read(bytes))!=-1){
out.write(bytes);
out.flush();//刷新}
in.close();
out.close();
异常处理
publicclassDemo2{publicstaticvoidmain(String[] args){
FileInputStream in = null;
FileOutputStream f = null;try{
in =newFileInputStream("a.txt");
f =newFileOutputStream("a.txt");byte[] bytes =newbyte[1024];int len =0;while((len = in.read(bytes))!=-1){
f.write(bytes,0, len);
f.flush();}}catch(IOException e){
e.printStackTrace();}finally{try{if(in != null){
in.close();}}catch(IOException e){
e.printStackTrace();}try{if(f != null){
f.close();}}catch(IOException e){
e.printStackTrace();}}}}