Java实战开发篇-9 文件和流

一、简介

1.文件的概念:数据在磁盘的唯一最小描述,上层应用程序必须通过文件来操作磁盘上的数据
注:Java中的File不是真实文件
网络下载的数据(文本 图片 视频 音频)写入缓存,读取缓存中的数据需要流来实现
2.读写文件的步骤一般为
(1)创建文件、创建目录(文件夹)
(2)判断文件是不是存在(判断目录是否存在)
(3)写入数据
(4)删除文件、删除目录
3.写入、读取数据
Java中的File是没有具体读取和写入的方法,需要通过输入输出流来操作
输出流:内存-外部(硬盘,网络,设备)
输入流:外部-内存
4.数据的存储有两种
(1)字节形式:图片,音频,视频,exe,这些是以二进制形式存储的
(2)字符形式:文本
所以读取方式有所不同
字节形式用字节流,一次读取一个字节,InputStream/OutputStream
字符形式用字符流,一次读取一个字符(两个字节)Reader/Writer
输入输出流都是抽象类,所以我们需要使用输入输出流的具体实现类
字节输入输出流:FileInputStream/FileOutputStream
字符输入输出流:FileReader/FileWriter

二、字节流

类1——创建一个文件

class creatFile {
    public static void creatFile() {
        //关键字File,让file指向一个对应文件,需要文件名
        //new File并不会自动创建文件
        File file = new File("C:\\Users\\Administrator\\Desktop\\1.text");
        //判断文件或者目录是否存在
        if (!file.exists()) {
            //3.创建文件,捕获异常
        try {
            file.createNewFile();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }
            }
            }

类2——创建一个目录

class creatDir {
    public static void creatDir() {
        File file = new File("C:\\Users\\Administrator\\Desktop\\", "file");
        if (!file.exists()) {
        try {
            file.mkdir();
            } catch (NullPointerException e) {
            e.printStackTrace();
            }
            }
            }
            }

类3——删除文件

class deleteFile {
    File file = new File("C:\\Users\\Administrator\\Desktop\\", "1.text");
    public void deleteFile() {
        if (file.exists()) {
            file.delete();
         }
         }
         }

类4——判断是文件还是目录

class FileOperation {
    File file = new File("C:\\Users\\Administrator\\Desktop\\代码");
    public void operation() {
        if (file.isFile()) {
            System.out.println("是文件");
        }
        if (file.isDirectory()) {
            System.out.println("是目录");
        }
        }
        }

类5——查看当前文件的所有内容

class List {
    File file = new File("C:\\Users\\Administrator\\Desktop\\", "1.text");
    String[] fileNameList = file.list();
    public void List() {
        for (String name : fileNameList) {
            System.out.print(name);//输出所有列表的名称
        }
        }
        }

类6——过滤文件(按要求筛选文件)

class Choose {
    File file = new File("C:\\Users\\Administrator\\Desktop\\", "1.text");
    public void choose() {
        String[] chooseNameList = file.list(new FilenameFilter() {
                //筛选文件需要实现FilenameFilter类,这里使用匿名内部类减少代码量
            @Override
            public boolean accept(File dir, String name) {
                //如果返回true,当前文件会被选中
                //如果返回false,当前文件会被过滤掉
                File f = new File(dir, name);
                if (f.isDirectory()) {
                    return true;
                }
                return false;
            }
            });
            }
            }

类7——写入数据

class Write {
    String des = "C:\\Users\\Administrator\\Desktop\\";

    public static void WriteToFile(String des) {
        //1.准备数据
        String text = "Hello World";
        FileWriter fw = null;
        //2.判断是需要字符流还是字节流
        try {
            //3.写入数据
            fw = new FileWriter(des);
            fw.write(text);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }
            }

类8——复制字节型文件

class CopyChar {
    public static void CopyImageToFile(String src, String des) {
        //1.将图片读取到内存中
        //字节输入流FileInputStream
        //2.将内存中的数据写入到磁盘中
        //字节流 输出流 FileOutputStream
        //凡是实现了closeable接口的类,都可以在try()括号内部创建对象
        //当try代码块执行完毕或者有异常,系统自动close
        try (FileInputStream inf = new FileInputStream(src);
             FileOutputStream outf = new FileOutputStream(des)) {
            int b;
            //byte[] bytes = new byte[1024];操作一个字节数组,解决read()效率低的问题
            while (true) {
                b = inf.read();
                //read();方法是一个一个字节的读,当文件较大时,效率就会非常低
                //b = inf.read(byte);
                if (b == -1) {
                    break;
                }//当读取完毕后返回值默认为-1,操作字节数组时是一样的
                outf.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
        }

类9——复制字符型文件

class CopyText {
    public static void CopyTextToFile(String src, String des) {
        //复制字符和复制字节方法是完全一样的,只是关键字不一样
        try (FileReader inf = new FileReader(src);
             FileWriter outf = new FileWriter(des)) {
            int b;
            //byte[] bytes = new byte[1024];操作一个字符数组
            while (true) {
                b = inf.read();
                //b = inf.read(byte);
                if (b == -1) {
                    break;
                }
                outf.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
        }

三、处理流——缓冲流

缓冲输入流BufferedInputStream BufferedReader
缓冲输出流BufferedOutputStream BufferedWriter
虽然使用了处理流比较快,但是真正读取数据的是节点流
1.必须先创建节点流对象,将数据从磁盘读到内存缓冲区
2.将内存缓冲区的数据读到处理流对应的缓冲区
3.从处理流的缓冲区将数据读取到对应的地方
输入输出重定向——打印流(PrintStream)指定输入输出的位置(默认是输出到终端)

类1——用处理流复制字节

class BufferChar{
    public void Operation(String scr,String des){
        BufferedOutputStream bos = null;
        try {
            //创建缓冲输入流
            FileInputStream fis = new FileInputStream(scr);
            BufferedInputStream bis = new BufferedInputStream(fis);
            //创建缓冲输出流
            FileOutputStream fos = new FileOutputStream(des);
            bos = new BufferedOutputStream(fos);
            int b;
            while((b = bis.read())!= -1){
                bos.write(b);
            }
            bos.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }
            }

类2——用处理流复制字符

class BufferText{
    public void Operation(String scr,String des){
        BufferedWriter bw = null;
        try{
            //创建输入流
            FileInputStream fis = new FileInputStream(scr);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            //创建输出流
            FileOutputStream fos = new FileOutputStream(des);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            bw = new BufferedWriter(osw);
            int b;
            while((b = br.read())!= -1){
                bw.write(b);
            }
            bw.flush();//当使用处理读取和输出时,需要调用flush()来刷新数据流
           }catch (Exception e){
            e.printStackTrace();
           }finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }

类3——重定向输入输出——在指定位置输出、在指定位置输入

class ReDirection{
    public void redirection_out(String des){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(des);
            PrintStream ps = new PrintStream(fos);//重定向输出,在指定位置输出
            System.setOut(ps);
            System.out.println("Hello World");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }
    public void redirection_in(String src){
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(src);
            Scanner scanner = new Scanner(fis);//重定向输入,在指定位置输入
            while (scanner.hasNext()){
                //把所有行的内容显示出来(默认只输出一行,所以写循环)
                System.out.println(scanner.next());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            }
            }

四、对象处理

把一个对象通过文件的方式存储和读取

class Save_Read_Object{
    class Person implements Serializable{
        int age;
        String name;
        public Person(int age, String name) {
            this.age = age;
            this.name = name;
        }
        }
    public void saveobject(String des) {
        try {
            FileOutputStream fos = new FileOutputStream(des);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            Person p = new Person(18,"Jack");
            oos.writeObject(p);
        }catch (Exception e){
            e.printStackTrace();
        }
        }//将对象保存在指定文件里面
    public void readobject(String src){
        try{
            FileInputStream fis = new FileInputStream(src);
            ObjectInputStream ois = new ObjectInputStream(fis);
          Person p = (Person)ois.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }
        }//从指定文件里面读取对象
        }

五、RandomAccessFile类

当一个文件存在的时候,写入数据时会把原来的文件覆盖掉
如果不想发生此情况,需要使用RandomAccessFile

class RandromAccess{
    public void randomaccess(String src){
        try {
            RandomAccessFile raf = new RandomAccessFile(src,"rw");
            //有几种模式mode:r,rw,rws
            //r为只读,rw为可读写,rws为同时读写
        }catch (Exception e){
            e.printStackTrace();
        }
        }
        }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354

推荐阅读更多精彩内容