字节流及其使用
- FileOutputStream
//传入需要写入的文件路径, //续写开关是个布尔值,不写默认清空,使用true表示不清空文件 FileOutputStream fos = new FileOutputStream("文件",续写开关); fos.write(需要写的数据); fis.close();//释放资源
- FileInputStream
FileInputStream fis = new FileInputStream("文件"); fw.read(数据); fw.close();
- 复制文件演示
需要同时使用两个流进行读写,所以我们要一直读一直写,使用循环读取。
读取的时候字节流会有一个结束标记为-1,表示当前文件已读取完毕,没有字节了
public class CopyTxtDemo { public static void main(String[] args) throws IOException { //根据数据源创建字节输入流对象 FileInputStream fis = new FileInputStream("C:\\a.txt"); //根据目的地创建字节输出流对象 FileOutputStream fos = new FileOutputStream("d:\\a.txt"); //循环读写数据,一次读取一个字节,写入一个节,直到读到结束标记 int by;//定义一个变量表示当前在读什么 while ((by=fis.read())!=-1) { fos.write(by);//传入读到的数据进行写入 } //释放资源 fos.close(); fis.close(); } }
字节流缓冲流
- 字节流缓冲流就是加速用的,传入的参数就是字节流
- API:
- BufferedInputStream
- FileOutputStream
- 文件复制演示
public class CopyAviDemo { public static void main(String[] args) throws IOException { //字节缓冲流一次读写一个字节数组 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("c:\\a.avi")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:\\b.avi")); byte[] bys = new byte[1024]; int len; while ((len=bis.read(bys))!=-1) { bos.write(bys,0,len); } bos.close(); bis.close(); } }
字符流及其使用
- FileWriter
FileWriter fw = new FileWriter("文件",续写开关); fw.write(数据); //刷新流,之后还可以写数据 flush() //fw.write(数据); fw.close();//释放资源
- FileReader
FileReader fr = new FileReader("文件"); fr.read(数据); fr.close();
字符流缓冲流
- 同样是给字符流加速的,进行高效的读写
- 创建时传入字符流对象
- 常用方法
- BufferedWriter
- newLine() ,特有方法,换行
- BufferedReader
- readLine() ,特有方法,读一行