文件和IO流

file

  • File,是文件和目录路径名的抽象表示
  • File 只关注文件本身的信息,而不能操作文件里面的内容

File类 – 表示文件或文件夹,不能对文件里的数据进行操作对文件里的数据进行操作的是:IO流

File 构造方法

  • File(File parent, File child)
  • File(String pathname)
  • File(String parent, String child)

File的创建

  • createNewFile():创建新的空文件
  • mkdir():创建此抽象路径名指定的目录
  • mkdirs():创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。

常用方法

public class Test01 {
	public static void main(String[] args) {
		/**
		 * 知识点:File类(文件类)
		 * 含义:是文件和目录路径名(文件夹)的抽象表示
		 * 注意:File只关注文件本身的信息,而不能操作文件里面的内容
		 * 需求1:通过程序,获取已知文件的信息
		 */
		//创建File类对象
		File file = new File("E:\\test.txt");

		System.out.println("获取绝对路径:" + file.getAbsolutePath());
		System.out.println("获取文件名:" + file.getName());
		System.out.println("是否可读" + file.canRead());
		System.out.println("是否可写" + file.canWrite());
		System.out.println("是否隐藏" + file.isHidden());
		System.out.println("获取文件长度(字节)" + file.length());
		System.out.println("判断是否是文件:" + file.isFile());
		System.out.println("判断是否是文件夹:" + file.isDirectory());
		System.out.println("判断文件是否存在:" + file.exists());


		SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
		System.out.println("最后修改时间:" + sdf.format(file.lastModified()));

	}
}

相对路径 和 绝对路径

public static void main(String[] args) {
		/**
		 * 相对路径:相对于项目的路径
		 * 绝对路径:路径中包含盘符(具体路径)
		 */
		//相对路径->test.txt ,存在于当前项目的src下
		File file = new File("test.txt");

		//绝对路径->C:\Users\ZHC\Desktop\test.txt
		System.out.println("获取绝对路径:" + file.getAbsolutePath());

	}

应用

需求1:通过程序,判断指定路径的文件是否存在,如果不存在,则创建该文件。下面按各种情况来解决该问题

  1. 目录已存在的情况
  2. 有一个层级的目录不存在的情况
  3. 有多个层级的目录不存在的情况
public static void main(String[] args) throws IOException {

    File file = new File("file01\\file02\\file03\\test.txt");

    //获取父路径对象(file01\\file02\\file03)
    File parentFile = file.getParentFile();

    if(!parentFile.exists()){//文件夹不存在
        //parentFile.mkdir();//创建一层文件夹
        parentFile.mkdirs();//创建多层文件夹
    }

    if(!file.exists()){//文件不存在
        file.createNewFile();//创建文件
    }
}

需求2:输出指定目录下的所有文件信息(只考虑当前目录,不考虑子目录)

public static void main(String[] args) {

    File file = new File("C:\\小幸福");

    //把该文件夹下所有的文件名放入list数组中
    //		String[] list = file.list();
    //		for (String name : list) {
    //			System.out.println(name);
    //		}

    //把该文件夹下所有的文件对象放入listFiles数组中
    File[] listFiles = file.listFiles();
    for (File f : listFiles) {
        System.out.println(f.getName() + " -- " + f.canRead() + " -- " + f.canWrite());
    }
}

需求3:输出指定目录下的所有文件信息(只考虑当前目录,不考虑子目录),要求只输出文件后缀名为txt的文件

public static void main(String[] args) {

    File file = new File("C:\\小幸福");

    //方法1.把该文件夹下所有的文件对象放入listFiles数组中
    File[] listFiles = file.listFiles();
    for (File f : listFiles) {
        if(f.isFile() && f.getName().endsWith(".txt")){
            System.out.println(f.getName());
        }
    }

    //方法2.使用过滤器遍历"C:\\小幸福"所有的文件,返回true就把该文件加入listFiles数组中
    File[] listFiles = file.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {

            File f = new File(dir, name);
            if(f.isFile() && name.endsWith(".txt")){
                return true;
            }
            return false;
        }
    });

    for (File f : listFiles) {
        System.out.println(f.getName());
    }
}

需求4:输出指定目录下的所有文件信息

  1. 要求只输出文件后缀名为txt的文件
  2. 列出当前目录及子目录中符合该条件的文件信息(递归)
public static void main(String[] args) {

    File file = new File("C:\\小幸福");

    method(file, ".txt");
}

public static void method(File file,String str){
    File[] listFiles = file.listFiles();
    for (File f : listFiles) {
        if(f.isDirectory()){//文件夹
            method(f, str);

        }else if(f.isFile()){//文件
            String name = f.getName();
            if(name.endsWith(str)){
                System.out.println(name);
            }
        }
    }
}

需求5:删除目录和里面的文件。这个目录里面有子目录,子目录里面可能也有子目录

public class Test01 {
	
	public static void main(String[] args) {
		
		File file = new File("C:\\Users\\hehanyu\\Desktop\\小幸福");
		
		method(file);		
	}
	
	public static void method(File file){
		File[] listFiles = file.listFiles();
		for (File f : listFiles) {
			if(f.isDirectory()){//文件夹
				method(f);
				f.delete();//只有空文件夹才能够被删除
			}else if(f.isFile()){//文件
				f.delete();
			}
		}
	}
}

需求6:实现拷贝文件及路径

public class Test01 {
	public static void main(String[] args) {
		
		//原文件夹
		File sourceFile = new File("C:\\Users\\hehanyu\\Desktop\\小幸福");
		//目标文件夹
		File targetFile = new File("C:\\Users\\hehanyu\\Desktop\\拷贝小幸福");
		
		method(sourceFile, targetFile);
	}
	
	//遍历原文件夹的方法
	public static void method(File sourceFile,File targetFile){
		File[] listFiles = sourceFile.listFiles();
		for (File file : listFiles) {
			if(file.isDirectory()){
				//创建目标文件夹中的子文件夹
				File f = new File(targetFile, file.getName());
				if(!f.exists()){
					f.mkdirs();
				}
				method(file, f);
			}else if(file.isFile()){
				copy(file, new File(targetFile, file.getName()));//拷贝文件
			}
		}
	}

	//拷贝文件夹
	public static void copy(File sourceFile,File targetFile){
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(sourceFile));
			bos = new BufferedOutputStream(new FileOutputStream(targetFile));
		
			byte[] bs = new byte[1024];
			int len;
			while((len = bis.read(bs)) != -1){
				bos.write(bs, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(bis != null){
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(bos != null){
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}	
}

IO流

含义

注意:站在程序的角度

I:In ,输入流,read读取(读取文件中的数据)

O:Out,输出流,writer写入(向文件里写入数据)

流:一点点的读取或者写入

分类

按照方向分:输入流、输出流

按照单位分:字节流、字符流

按照功能分:节点流/基础流、处理流(处理流包裹基础流,功能更强大)

字节流

InputStream 字节输入流的基类(抽象类)

OutputStream 字节输出流的基类(抽象类)

  • FileInputStream extends InputStream 文件字节输入流(基础流)
  • FileOutputStream extends OutputStream 文件字节输出流(基础流)
  • FilterInputStream extends InputStream 过滤器字节输入流(不常用)
  • FilterOutputStream extends OutputStream 过滤器字节输出流(不常用)
  • BufferedInputStream extends InputStream 带有缓冲区的字节输入流(处理流)
  • BufferedOutputStream extends OutputStream 带有缓冲区的字节输出流(处理流)

默认缓冲区大小为:8192字节

FileInputStream 文件字节输入流
public static void main(String[] args) throws IOException {
 	/**
		 * 需求:利用文件字节输入流读取文件中的数据
		 * 	1.文件存在的情况,读取一个字节
		 * 	2.文件不存在的情况,读取一个字节(经验:所有的输入流,文件不存在就报错)
		 *  3.一个一个字节的读取整个文件
		 * 	4.1024个1204个字节的读取整个文件
		 */
    //1.创建流对象
    FileInputStream fis = new FileInputStream("file\\fos.txt");

    //2读取数据
    //2.1 读取第一个字节,并返回ASCII
    //	int read = fis.read();
    //	System.out.println(read);//99
    //2.2 read()依次读取单个字节,读取到文件末尾返回-1
    //	int read;
    //	while((read = fis.read()) != -1){
    //		System.out.println((char)read);
    //	}
    //2.3 每次去读取bs长度的数据并放入bs数组中,返回有效字节数
    byte[] bs = new byte[1024];
    int len;
    while((len = fis.read(bs)) != -1){
        System.out.println(new String(bs, 0, len));
    }

    //3.关流
    fis.close();
}
FileOutputStream 文件字节输出流
public static void main(String[] args) throws IOException {
 	/**
		 * 需求:利用文件字节输出流向文件写入数据
		 * 	1.文件存在,则直接写入数据
		 * 	2.若文件不存在。(经验:所有的输出流,当文件不存在时自动创建)
		 * 	3.向文件末尾追加文件
		 */
    //1.创建流对象
    FileOutputStream fos = new FileOutputStream("file\\fos.txt");
    //向文件末尾追加数据
    //FileOutputStream fos = new FileOutputStream("file\\fos.txt",true);

    //2.写入数据
    //fos.write(97);//a  写入ASCII
    //fos.write("zxc123".getBytes());//zxc123
    fos.write("zxcv123".getBytes(), 2, 4);//cv12

    //3.关流
    fos.close();
}
拷贝文件(低效率)
public static void main(String[] args) {
 /**
	* 需求:拷贝文件:读一个字节,再写一个字节
	*/
    //处理异常
    FileInputStream fis = null;
    FileOutputStream fos = null;

    try {
        fis = new FileInputStream("file\\fos.txt");
        fos = new FileOutputStream("file\\copyByte.txt");
        int read;
        while((read = fis.read()) != -1){
            fos.write(read);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(fos != null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
public static void main(String[] args) {
    	/**
		 * 需求:拷贝文件:读一个字节,再写一个字节
		 */
    //利用JDK1.7的新特性处理异常
    try(FileInputStream fis = new FileInputStream("file\\fos.txt");
    	FileOutputStream fos = new FileOutputStream("file\\copyByte.txt")) {

        int read;
        while((read = fis.read()) != -1){
            fos.write(read);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) {
    /**
	* 需求:拷贝视频文件:读1024个字节,再写1024个字节
	*/

    try(FileInputStream fis = new FileInputStream("file\\学习.mp4");
        FileOutputStream fos = new FileOutputStream("file\\copy.mp4")) {

        byte[] bs = new byte[1024];
        int len;
        while((len = fis.read(bs)) != -1){
            fos.write(bs, 0, len);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
BufferedInputStream 带有缓冲区的字节输入流
public static void main(String[] args) throws IOException {
 /**
	* 需求:利用带有缓冲区的的字节输入流读取文件中的数据
	*/

    //1.创建流对象
    //使用默认的缓冲区(大小:8192字节)
    //BufferedInputStream bis = new BufferedInputStream(new FileInputStream("io.txt"));
    //自定义大小的缓冲区
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("io.txt"),10000);

    //2.读取数据
    byte[] bs = new byte[1024];
    int len;
    while((len = bis.read(bs)) != -1){
        System.out.println(new String(bs, 0, len));
    }

    //3.关流
    bis.close();

}
BufferedOutputStream 带有缓冲区的字节输出流
public static void main(String[] args) throws IOException {
 /**
	* 需求:利用带有缓冲区的的字节输出流向文件写入数据
	*/

    //1.创建流对象
    //使用默认的缓冲区(大小:8192字节)
    //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io.txt"));
    //自定义大小的缓冲区
    //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io.txt"),10000);
    //在文件末尾追加数据
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("io.txt",true));

    //2.写入数据
    bos.write("zxc123".getBytes());

    //3.关流
    bos.close();

}
复制文件(高效率)
public static void main(String[] args) {
 BufferedInputStream bis = null;
 BufferedOutputStream bos = null;

 try {
     bis = new BufferedInputStream(new FileInputStream("回顾.mp4"));
     bos = new BufferedOutputStream(new FileOutputStream("copy.mp4"));

     byte[] bs = new byte[1024];
     int len;
     while((len=bis.read(bs)) != -1){
         bos.write(bs, 0, len);
     }
 } catch (FileNotFoundException e) {
     e.printStackTrace();
 } catch (IOException e) {
     e.printStackTrace();
 }
 finally {
     if(bis!=null){
         try {
             bis.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
     if(bos!=null){
         try {
             bos.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 }
}

字符流

Reader 字符输入流的基类(抽象类)

Writer 字符输出流的基类(抽象类)

  • InputStreamReader extends Reader 字符输入转换流(字节流转换字符流)
  • OutputStreamWriter extends Writer 字符输出转换流(字节流转换字符流)

应用场景:获取到的流是字节流,但是要去做字符操作

注意:使用转换流都加编码格式

  • FileReader extends InputStreamReader 文件字符输入流
  • FileWriter extends OutputStreamWriter 文件字符输出流
  • BufferedReader extends Reader 带有缓冲区的字符输入流
  • BufferedWriter extends Writer 带有缓冲区的字符输出流

默认缓冲区大小:8192字符

OutputStreamWriter 字符输出转换流
public static void main(String[] args) throws IOException {
 /**
	* 需求:利用字符输出转换流,向文件写入数据
	*/

    //1.创建流对象
    //OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("file\\io.txt"));
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("file\\io.txt"),"GBK");

    //2.写入数据
    //osw.write(97);//写入ASCII
    //osw.write("小强吃饭睡觉觉~~");//写入字符串
    //osw.write("小强吃饭睡觉觉~~",2,7);//写入字符串,偏移量,写入字符的个数
    osw.write("小强吃饭睡觉觉~~".toCharArray());//写入字符数组
    osw.write("abc,123".toCharArray(),2,9);//写入字符数组,偏移量,写入字符个数

    //3.关流
    osw.close();
}
InputStreamReader 字符输入转换流
public static void main(String[] args) throws IOException {
 /**
	* 需求:利用字符输入转换流 读取文件中的数据(一个字符一个字符的读取)
	*/

    //1.创建流对象
    //InputStreamReader isr = new InputStreamReader(new FileInputStream("file\\io.txt"));
    //设置编码格式
    InputStreamReader isr = new InputStreamReader(new FileInputStream("file\\io.txt"),"UTF-8");

    //2.读取数据 
    int read;
    while((read = isr.read()) != -1){
        System.out.println((char)read);
    }

    //3.关流
    isr.close();
}
public static void main(String[] args) throws IOException {
    /**
	* 需求:利用字符输入转换流 读取文件中的数据(1024个字符1024个字符的读取)
	*/

    //1.创建流对象
    //InputStreamReader isr = new InputStreamReader(new FileInputStream("io.txt"));
    //设置编码格式
    InputStreamReader isr = new InputStreamReader(new FileInputStream("io.txt"),"UTF-8");

    //2.读取数据 
    char[] cs = new char[1024];
    int len;
    while((len = isr.read(cs)) != -1){
        System.out.println(new String(cs, 0, len));
    }

    //3.关流
    isr.close();
}
拷贝文本文件
public static void main(String[] args) throws IOException {
 /**
	* 拷贝文本文件
	*/
    InputStreamReader isr = new InputStreamReader(new FileInputStream("file\\io.txt"));
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("file\\copy.txt"));

    char[] cs = new char[1024];
    int len;
    while((len = isr.read(cs)) != -1){
        osw.write(cs, 0, len);
    }

    isr.close();
    osw.close();
}
FileWriter 文件字符输出流
public static void main(String[] args) throws IOException {
 /**
	* 需求:利用文件字符输出流 向文件写入数据
	*/
    //1.创建流对象
    //		FileWriter fw = new FileWriter("file\\fw.txt");
    //在文件末尾添加数据
    FileWriter fw = new FileWriter("file\\fw.txt",true);

    //2.写入数据
    fw.write("小强吃饭,睡觉觉~~~");

    //3.关流
    fw.close();

}
FileReader 文件字符输入流
public static void main(String[] args) throws IOException {
 /**
	* 需求:利用文件字符输入流 读取文件中的数据
	*/
    //1.创建流对象
    FileReader fr = new FileReader("file\\fw.txt");		
    //2.读取数据,1024个字符1024个字符的读取
    char[] cs = new char[1024];
    int len;
    while((len = fr.read(cs)) != -1){
        System.out.println(new String(cs, 0, len));
    }
    //3.关流
    fr.close();

}
拷贝文本文件(低效率)
public static void main(String[] args) throws IOException {
 /**
	* 需求:拷贝文本文件
	*/

    FileReader fr = new FileReader("file\\太古神王.txt");
    FileWriter fw = new FileWriter("file\\小说.txt");

    char[] cs = new char[1024];
    int len;
    while((len = fr.read(cs)) != -1){
        fw.write(cs,0,len);
    }

    fr.close();
    fw.close();	
}
BufferedWriter 带有缓冲区的字符输出流
public static void main(String[] args) throws IOException {
 /**
	* 需求:利用带有缓冲区的字符输出流 向文件写入数据
	*/
    //默认缓冲区:8192字符
    //BufferedWriter bw = new BufferedWriter(new FileWriter("file\\io.txt"));

    //自定义缓冲区:10000
    //BufferedWriter bw = new BufferedWriter(new FileWriter("file\\io.txt"), 10000);

    //在文件末尾追加数据
    //BufferedWriter bw = new BufferedWriter(new FileWriter("file\\io.txt",true));

    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file\\io.txt"),"GBK"));

    //2.写入数据
    bw.write("小强吃饭睡觉觉~~");

    //3.关流
    bw.close();
}
BufferedReader 带有缓冲区的字符输入流
public static void main(String[] args) throws IOException {
 /**
	* 需求:利用带有缓冲区的字符输入流 读取文件中的数据
	*/
    //默认缓冲区:8192字符
    //BufferedReader br = new BufferedReader(new FileReader("file\\io.txt"));
    //自定义缓冲区:10000
    //BufferedReader br = new BufferedReader(new FileReader("file\\io.txt"),10000);

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("file\\io.txt"),"GBK"));

    //读取数据,1024个字符1024个字符的读取
    char[] cs = new char[10000];
    int len;
    while((len = br.read(cs)) != -1){
        System.out.println(new String(cs, 0, len));
    }

    //关流
    br.close();
}
public static void main(String[] args) throws IOException {
    /**
	* 需求:利用带有缓冲区的字符输入流 读取文件中的数据
	*/
    //创建流对象
    BufferedReader br = new BufferedReader(new FileReader("file\\io.txt"));
    //读取数据 一行一行的读取
    String str;
    while((str = br.readLine()) != null){
        System.out.println(str);
    }

    //关流
    br.close();
}
拷贝文本文件(高效率)
public static void main(String[] args) throws IOException {
    /**
		 * 	拷贝文本文件
		 */
    BufferedReader br = new BufferedReader(new FileReader("file\\太古神王.txt"));
    BufferedWriter bw = new BufferedWriter(new FileWriter("file\\小说.txt"));		

    String str;
    while((str = br.readLine()) != null){
        bw.write(str);
        bw.newLine();//换行,最终结果比原文件多一行
    }

    //char[] cs = new char[1024];
    //int len;
    //while((len = br.read(cs)) != -1){
    //	  bw.write(cs, 0, len);
    //}

    br.close();
    bw.close();
}

各种流

对象流

ObjectInputStream 对象输入流

ObjectOutputStream 对象输入流

序列化概念:

序列化:将程序中的对象写入到文件中 — 钝化

反序列化:将文件中的对象读取到程序中 — 活化

一个类的对象要想通过对象流写入到文件中,该类就必须实现序列化接口(Serializable)

Serializable叫做序列化接口,该接口没有让我们去实现任何的方法,这种接口叫做标记型接口

transient修饰属性后,该属性不会随着对象写入到文件中

static静态属性也不会随着对象写入到文件中

ObjectOutputStream
public static void main(String[] args) throws IOException, ClassNotFoundException {
    /**
	* 需求:将数据写入到文件中
	*/
    //1.创建流对象
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file\\obj.txt"));

    //2.写入数据
    oos.writeInt(123);
    oos.writeDouble(12.123);
    oos.writeObject(new Date());

    //3.关流
    oos.close();

}
ObjectInputStream
public static void main(String[] args) throws IOException, ClassNotFoundException {
    /**
	* 需求:读取文件中的数据
	*/
    //1.创建流对象
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file\\obj.txt"));

    //2.读取数据(注意:读取顺序和写入顺序必须一致)
    System.out.println(ois.readInt());
    System.out.println(ois.readDouble());
    System.out.println((Date)ois.readObject());

    //3.关流
    ois.close();

}
自定义对象的存取

Student类

public class Student implements Serializable{
	
	//设置序列化版本号(防止因实体类改变,而导致无法反序列化)
	private static final long serialVersionUID = 3110841416749609487L;
	
	private String name;
	private transient char sex;
	private int age;
	private String classId;
	private String id;
	
	public Student() {
	}
	
	public Student(String classId, String id) {
		this.classId = classId;
		this.id = id;
	}

	public Student(String name, char sex, int age, String classId, String id) {
		this.name = name;
		this.sex = sex;
		this.age = age;
		this.classId = classId;
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public char getSex() {
		return sex;
	}

	public void setSex(char sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getClassId() {
		return classId;
	}

	public void setClassId(String classId) {
		this.classId = classId;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	@Override
	public String toString() {
		return name + "\t" + sex + "\t" + age + "\t" + classId + "\t" + id;
	}
}

将对象写入到文件中(序列化)

public class Test03 {
	
	public static void main(String[] args) throws IOException{
		
		//1.创建流对象
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("io.txt"));
		
		//2.写入数据
		oos.writeObject(new Student("林成", '男', 21, "2107", "001"));
		oos.writeObject(new Student("李科", '男', 28, "2107", "002"));
		oos.writeObject(new Student("卢永刚", '男', 20, "2107", "003"));
		oos.writeObject(null);
		
		//3.关流
		oos.close();
		
	}
}

读取文件中的对象(反序列化)

public class Test04 {
	
	public static void main(String[] args) throws IOException, ClassNotFoundException{
		//1.创建流对象
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("io.txt"));
		
		//2.读取数据(注意:读取顺序和写入顺序必须一致)
		Student stu;
		while((stu = (Student) ois.readObject()) != null){
			System.out.println(stu);
		}
		
		//3.关流
		ois.close();
		
	}
}
打印流
PrintStream 字节打印流
public static void main(String[] args) throws IOException {

    //1.创建打印流
    //PrintStream ps = new PrintStream("io.txt");
    //在文件末尾追加数据
    PrintStream ps = new PrintStream(new FileOutputStream("io.txt",true));

    //2.写入数据
    ps.println("小强睡觉觉~~");

    //3.关流
    ps.close();

}
PrintWriter 字符打印流
public static void main(String[] args) throws IOException {
    /**
	* 知识点:字符打印流 PrintWriter
	*/

    //1.创建打印流
    //PrintWriter pw = new PrintWriter("io.txt");

    PrintWriter pw = new PrintWriter(new FileOutputStream("io.txt",true));

    //2.写入数据
    pw.write("小明吃饭睡觉觉~~~");

    //3.关流
    pw.close();

}
随机访问流

写数据 - rw

public static void main(String[] args) throws IOException {
    /**
	* 需求:利用随机访问流 向 文件写入数据
	* 	1.写入数字、英文、中文
	* 	2.在文件末尾追加内容
	*/

    //1.创建流对象
    File file = new File("io.txt");
    RandomAccessFile w = new RandomAccessFile(file, "rw");

    //2.1写入数据
    //		w.write("123ab哈哈哈".getBytes());
    //2.2追加数据
    //设置指针在文件末尾
    w.seek(file.length());
    //写入数据
    w.write("123木头人".getBytes());

    //3.关流
    w.close();
}
public static void main(String[] args) throws IOException {
    /**
	* 需求:从英文处开始写入数据
	*/
    //1. 创建流对象
    File file = new File("io.txt");
    RandomAccessFile w = new RandomAccessFile(file, "rw");

    //设置指针
    w.seek(3);

    //2.写入数据(从指针处开始替换数据)
    w.write("88".getBytes());

    //3.关流
    w.close();

}

读取文件 - r

public static void main(String[] args) throws IOException {
    /**
	* 需求:利用随机访问流 读取文件的数据,从英文处开始读取
	*/

    //1. 创建流对象
    RandomAccessFile r = new RandomAccessFile("io.txt", "r");

    //设置指针
    r.seek(3);

    //读取数据
    byte[] bs = new byte[1024];
    int len;
    while((len = r.read(bs)) != -1){
        System.out.println(new String(bs,0,len));
    }

    //关流
    r.close();
}
重定向
public static void main(String[] args) throws IOException {
    /**
	* 知识点:重定向 System.setIn()
	* 
	//获取系统标准的输入流(方向:控制台->程序)
	InputStream in = System.in;
	*/
    //重定向:(方向:文件->程序)
    System.setIn(new FileInputStream("io.txt"));

    //获取的是重定向后的InputStream
    InputStream in = System.in;

    Scanner sc = new Scanner(in);

    String next = sc.next();

    System.out.println(next);

    sc.close();

}
public static void main(String[] args) throws IOException {
    /**
	* 知识点:重定向 System.setOut()
	* 
	//获取系统标准的输出流(方向:程序->控制台)
 	PrintStream out = System.out;
	*/
    //重定向:(方向:文件->程序)
    System.setOut(new PrintStream(new FileOutputStream("io.txt",true)));

    //获取的是重定向后的InputStream
    PrintStream out = System.out;

    out.println("哈哈哈~");
}
内存流

注:内存流无法关闭

public static void main(String[] args) throws IOException {
    /**
	* 知识点:内存流
	*/

    //创建内存输入流(创建流时就将数据放入到内存中)
    ByteArrayInputStream bis = new ByteArrayInputStream("123abc".getBytes());

    //获取数据
    byte[] bs = new byte[1024];
    int len;
    while((len = bis.read(bs)) != -1){
        System.out.println(new String(bs, 0, len));
    }
}
public static void main(String[] args) throws IOException {
    /**
	* 知识点:内存流
	*/

    //创建内存输出流(创建流时就将数据放入到内存中)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    //写入数据
    baos.write("123ABC木头人".getBytes());

    //一次性读取数据
    System.out.println(baos.toString());
    System.out.println(new String(baos.toByteArray()));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值