java学习:IO流

1、File的使用

java.io.file类:表示文本或文件夹(目录路径),与平台无关的一种抽象表示方式。

可以进行新建、删除、重命名等操作,但是不能操作文件内容本身,如果需要访问文件内容则使用输入输出流。

构造器:File(String pathname)

@Test
public void test() {//创建File对象 --- 可以表示一个不存在的路径或文件
File file = new File("hello.txt");
System.out.println(file); //hello.txt
System.out.println(file.exists());//false
}

File的常用方法:

file.exists() 文件是否存在

file.getName() 获得文件名

file.getAbsolutePath() 绝对路径

file.isDirectory() 是不是文件夹

file.isFile() 是不是文件

file.list() 当前目录下所有文件和文件夹名称

mkdir() 创建文件夹,只能创建一级目录

mkdirs() 创建多级目录

creatNewFile() 新建文件

2、IO的原理和使用

IO是input和output的缩写,用于处理设备之间的数据传输,如读写文件、网络通信等。

java.io包下提供了许多“”流 和接口。java程序中,堆数据的输入输出以流(stream)的方式进行。

输入input:读取外部数据(硬盘、网络)到程序(内存)中。读

输出output:将程序(内存)中的数据传输到外部(硬盘、网络)。写

2.1 流的分类

方向:输入输出

大小:字节、字符

功能(越来越强):节点(文件)流、处理流

2.2 四个抽象基类(抽象类)
字节流字符流
输入InputStreamRead
输出流OutputStreamWriter

其他所有流都是这4个基类的具体实现类

img

2.3 常见的文件流、处理流
文件流缓冲流
FileInputStreamBufferedInputStream
FileOutputStreamBufferedOutputStream
FilereaderBufferedReader
FileWriterBufferedWrite
2.3.1字符流(后缀是Read\Write)
(1)读取文件(FileReader)

FileReader的read()方法

@Test
public void test2() throws IOException {
    FileReader fr = null;
    try {
        //创建File文件,指明要操作的文件
        File f = new File("hello world");
        //创建流
        fr = new FileReader(f);
        //读取数据
        //int data = fr.read();
        //while(data != -1) {
        //		System.out.println((char)data);
        //		data = fr.read();
        int data;
        while((data = fr.read())!= -1) {
            System.out.println((char)data);
        }
    }finally {
        if (fr != null) {
            fr.close();
        }
    }

}

FileReader的read(char[] cbuf)方法,返回len–The number of characters read。

@Test
	public void test3() throws IOException  {
		FileReader fr = null;
		try {
			//创建File文件,指明要操作的文件
			File f = new File("hello world");
			//创建流
			fr = new FileReader(f);
			//读取数据
			char[] cbuf = new char[4];
			int len;
			while((len = fr.read(cbuf))!= -1) {
				//System.out.println(cbuf);//会多打
				System.out.println(new String(cbuf,0,len));
				//public String(char value[], int offset, int count) String有参构造方法
			}
		}finally {
			if (fr != null) {
				fr.close();
			}
		}
		
	}
(2)写文件(FileWriter)

输出操作,对应的File如果不存在,会自动创建一个对应文件。

FileWriter(fifile, false) : 对原有文件覆盖 (默认状态) 。

FileWriter(fifile, true) : 对原有文件追加 。

@Test
public void test5() throws IOException { 
    FileWriter fw = null; 
    try {
        // 1、创建File对象,指明需要操作的文件 
        File f = new File("hello.txt"); 
        // 2、创建流 //如果设置为true则累加 
        fw = new FileWriter(f, true); 
        //3、写操作 
        fw.write("I have a dream!\n"); 
        fw.write("you need to have a dream"); 
		//fw.flush(); 
    } finally { 
        // 4、关闭资源 
        if (fw != null) {
            fw.close(); 
        } 
    } 
}
(3)边读边写
@Test public void test6() throws IOException { 
    //1、创建读取的文件 
    File srcFile = new File("hello.txt"); 
    File destFile = new File("hello2.txt"); 
    //2、创建输入输出流 
    Reader r = new FileReader(srcFile); 
    Writer w = new FileWriter(destFile); 
    //3、边读边写 
    char[] chuf = new char[4];
    while((len = r.read(chuf)) != -1) { 
     	//4、写 每次写入len长度个字符 
        w.write(chuf,0,len);
    }
    //4、关闭资源 
    if(r != null) {
        r.close(); 
    }if(w != null) { 
        w.close(); 
    } 
}
2.3.2 字节流

FileInputStream读文件

@Test public void test7() throws IOException {
    //1、造文件
    File f = new File("hello.txt"); 
    //2、造管道 FileInputStream input = new FileInputStream(f); 
    //3、读 
    F1 byte[] b = new byte[2]; //字节数组 -- - 2个字节16个0/1, 一个汉字2字节 
    //如果设置为1个字节,则读取的内容乱码, 
    //原因:汉字占两个字节,每次读取一个字节,这一个字节的信息,不能表示出来 
    int len; //记录每次读取的字节个数 
    while((len = input.read(b)) != -1) { 
        System.out.println(new String(b, 0, len)); 
    }
    //4、关闭资源 
    input.close(); 
}

复制图片:

@Test public void test8() throws IOException {
    //创建流 
    FileInputStream fis = new FileInputStream("001.png"); 
    FileOutputStream fos = new FileOutputStream("002.jpg"); 
    //复制,边读边写 
    byte[] b = new byte[1024]; 
    int len; 
    while((len = fis.read(b)) != -1) { 
        fos.write(b, 0, len); 
    }
    //关闭资源 
    fis.close(); 
    fos.close(); 
}

复制视频:

public void copyFile(String srcPath, String destPath) throws IOException { 		
    FileInputStream fis = null; 
    FileOutputStream fos = null; 
    try {
        fis = new FileInputStream(srcPath); 
        fos = new FileOutputStream(destPath); 
        //复制 
        byte[] b = new byte[1024]; 
        int len; 
        while ((len = fis.read(b)) != -1) {
            fos.write(b, 0, len); 
        } 
    } catch (Exception e) { 
        e.printStackTrace(); 
    }finally {
        if(fis != null) {
            fis.close(); 
        }if(fos != null) {
            fos.close(); 
        } 
    } 
}@Test public void test9() throws IOException {
    long start = System.currentTimeMillis();
    String srcPath = ""; 
    //视频文件 
    String destPath = "";
    //复制文件 
    copyFile(srcPath, destPath); 
    long end = System.currentTimeMillis(); 
    System.out.println("复制视频花费时间为: " + (end - start)); }
2.3.2 缓存流

为了提高数据的读写速度,Java提供了带缓冲功能的流,在使用这些流时,会创建一个内部缓冲数组。默认8kb缓冲区

@Test public void test10() throws IOException { 
    //1造文件 
    File srcFile = new File("001.png"); 
    File destFile = new File("002.png"); 
    //2.创建流 
    //创建节点流
	FileInputStream fis = new FileInputStream(srcFile); 
    FileOutputStream fos = new FileOutputStream(destFile); 
    //创建处理流 ---- 缓存流 
    BufferedInputStream bis = new BufferedInputStream(fis); 
    BufferedOutputStream bos = new BufferedOutputStream(fos); 
    //3.复制,读写 
    byte[] b = new byte[10]; 
    int len; while((len = bis.read(b)) != -1) {
        bos.write(b, 0, len); 
    }
    //4关闭资源
    bis.close(); 
    //缓存流关闭,节点流自然关闭,关闭外层,内层自动关闭 
    bos.close(); 
}
2.3 对象序列化
(1)定义

序列化:用ObjectOutputStream类保存基本类型数据或对象。

反序列化:使用ObjectInputStream类读取基本类型数据或对象 。

不能序列化static和transient修饰的成员变量。

对象序列化机制允许把内存中的对象转换成与平台无关的二进制流,从而把这种二进制数据保存在硬盘中。获者通过网络将这种二进制数据传输到另一个网络节点。当程序获取到这种二进制流,就可以恢复成原来java对象。

对象序列化需要实现Serializable接口。

(2)序列化步骤
  • 1、创建ObjectOutputStream
  • 2、调用writeObject()方法输出可以序列化的对象
  • 3、注意写入一次,操作flflush一次
//1. 
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
//2 
oos.writeObject(new Person("小米",20)); 
//3 
oos.flush(); 
//4  
oos.close();
(3)反序列化步骤
  • 1、创建ObjectInputStream
  • 2、调用readObject方法读取流中的对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
Person p = (Person)ois.readObject();
System.out.println(p);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值