自己怎么做家政网站如何做网站推广优化
随时随地技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
1.流按照方向分:输入流,输出流。流的方向以内存作为参照物。
如果从数据源中将数据读取到内存叫输入流,也叫读取流。
如果将内存中的数据写入到数据源,叫输出流,也叫写入流。
2.流按照类型分 :字节流、字符流、对象流。
在数据传输的底层部分,所有的数据都以二进制方式传输。所以真正的流只有字节流。至于字符流和对象流是为了方便程序员更好的对字符串和对象进行操作。所以在字节流基础上作了一层包装,简化了这些操作。
InputStream 是读取字节流的父类。该类是抽象类,提供read()抽象方法。每个子类根据自己数据源的特点分别
重写read()。达到相同的行为不同的实现的效果。满足开闭原则。
3.流操作步骤:1.建立流。2.操作流。3.关闭流
读取文本文件首选字符流,但读取音频、视频、图片这样的二进制文件,只能用字节流
流使用完成后,一定要关闭,否则,不但浪费系统资源,而且写入流有可能写不进文件。
字节流的使用示例:
读取流:
package com;import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;public class InputStreamTest {public InputStreamTest() {InputStream in = null;try {// 创建文件读取字节流in = new FileInputStream("c:/p1.jpg");// 读取流中的一个字节,该字节就是数据。// 不断读取文件中的数据,读取到文件末尾,则返回-1// 第一种数据读取方式,一次读取一个字节,内存消耗小,效率低int date = -1;while ((date = in.read()) != -1) {System.out.println(date);}// 读取数据的第二种方式:一次读取一定数量的字节,并将其存储在缓冲区数组 b 中byte[] by = new byte[1024];// 存放读取的字节数int len = 0;// 将流中的数据读取到byte数组,一次读取1024字节。返回当前读取得字节数。while ((len = in.read(by)) != -1) {System.out.println(len);}// 读取数据的第三种方式:将输入流中最多 len个数据字节读入 byte 数组。0 : 数组 b 中将写入数据的初始偏移量。byte[] by1 = new byte[1024];int len1 = 0;while ((len1 = in.read(by1, 0, 700)) != -1) {System.out.println(len1);}} catch (Exception e) {e.printStackTrace();} finally {try {// 关闭流in.close();} catch (IOException e) {e.printStackTrace();}}}public static void main(String[] args) {new InputStreamTest();}}
写入流:
package com;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;public class OutputStreamTest {public OutputStreamTest (){OutputStream out=null;File f=new File("aa");//创建一个文件对象if(!f.exists()){//判断目录是否存在f.mkdir(); //创建目录}System.out.println(f.getAbsolutePath());// 得到当前文件的绝对路径try {//创建写入流,一般写入的文件在本工程中out=new FileOutputStream("aa/2.txt");out.write(65);out.write(68);out.write(69);} catch (Exception e) {e.printStackTrace();}finally{try {out.close();} catch (IOException e) {e.printStackTrace();}}}public static void main(String[] args) {new OutputStreamTest();}
}
读取流和写入流的结合使用:文件复制
package com;import java.io.FileInputStream;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;public class CopyFile {public CopyFile() {InputStream in = null;// 读取流,读取源文件OutputStream out = null;// 写入流,写入目标文件try {// 创建流in = new FileInputStream("c:/p1.jpg");out = new FileOutputStream("p1.jpg");byte[] by = new byte[1024];int len = 0;while ((len = in.read(by)) != -1) {out.write(by, 0, len);// 写入数据,读取了多少字节,写入多少字节}} catch (Exception e) {e.printStackTrace();} finally {try {// 关闭流in.close();out.close();} catch (IOException e) {e.printStackTrace();}}}public static void main(String[] args) {new CopyFile();}}