File,IO流与IO流异常处理

File

File类用于封装一个文件路径,可以描述一个文件或文件夹,通过File对象可以读取文件或者文件夹的属性数据,但是读取文件的内容,就需要使用IO流技术。

构造函数
 public static void demo() {
        File file = new File("E:/Demo");
        File file1 = new File("E:", "Demo1");
        File file2 = new File(file, "Test");
}
创建
public static void demo() throws IOException {
        String filePath = "E:/Demo/Test";
        File file = new File(filePath);
        file.mkdir();//创建单级文件夹,"E:/Demo"
        file.mkdirs(); //创建多级文件夹,"E:/Demo/Test"
        file.createNewFile();//创建文件,"E:/Demo/Test.txt"
}
删除
public static void demo() {
        String filePath = "E:/Demo";
        File file = new File(filePath);
        file.delete();
        file.deleteOnExit();
}
重命名
 public static void demo() {
        File file1 = new File("E:", "Demo");
        file1.mkdir();

        File file2 = new File("E:", "Changed");
        file1.renameTo(file2); //重命名
    }
判断
 public static void demo() {
        File file = new File("E:", "Demo");
        boolean exists = file.exists(); //判断文件是否存在
        boolean directory = file.isDirectory(); //判断是否为文件夹
        boolean file1 = file.isFile();//判断是否为文件
        boolean hidden = file.isHidden();//判断文件是否隐藏
        boolean absolute = file.isAbsolute();//判断是否为绝对路径
}
获取
 public static void demo() {
        File file = new File("E:", "Demo");
        file.mkdir();

        String name = file.getName();
        String path = file.getPath();
        String absolutePath = file.getAbsolutePath();
        String parent = file.getParent();
        long length = file.length();

        long lastModified = file.lastModified();
        Date date = new Date(lastModified);
        SimpleDateFormat format = new SimpleDateFormat("yyyy年HH月dd日 hh:MM:ss");
        System.out.println(format.format(date));
    }
文件夹相关
 public static void demo() {
        File file = new File("E:", "Demo");
        file.mkdir();

        String[] list = file.list();//获取当前文件夹下的所有子文件与子文件夹名
        File[] files = file.listFiles();//获取当前文件夹下的所有子文件与子文件夹
}

IO流

OutputStream(字节输出流)
FileOutputStream(字节输出流)

public static void write(File file) {

        try (
                //如果目标文件不存在,会自动创建目标文件对象
                //如果目标文件已经存在,会先清空目标文件中的数据然后再写入数据
                //FileOutputStream fos = new FileOutputStream(file)

                //如果目标文件已存在,想要追加数据,使用此构造方法
                FileOutputStream fos = new FileOutputStream(file, true)
        ) {
            String str = "Demo write data";

            //虽然接收的是一个int类型的数据,但是真正写出的只是一个字节的数据
            //只是把低八位的二进制数据写出,其他二十四位数据全部丢弃
            fos.write(str.getBytes());
            fos.flush();
            System.out.println("写入成功");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
BufferedOutputStream(缓冲字节输出流)

 public static void write(File file) {
        try (
                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
        ) {

            String str = "Demo write data";

            //先把数据写到它内部维护的字节数组中
            bos.write(str.getBytes());
            //如果真正写到硬盘上就需要调用它的flush,或close方法
            // 或者内部维护的字节数据已经填满数据的时候也会刷出去
            bos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
InputStream(字节输入流)
FileInputStream(字节输入流)

public static void read(File file) {
        try (
                FileInputStream fis = new FileInputStream(file)
        ) {
            //用于声明文件读取到那里
            int len;

            // 建立缓冲字节数组,大小一般用1024倍数,理论上越高效率越高
            byte bur[] = new byte[1024];

            // 如果使用read传入字节数组,那么数据是存储到字节数组的,
            // 返回值是存储到缓冲数组中字节个数,-1为结束
            while ((len = fis.read(bur)) != -1) {
                System.out.println(new String(bur, 0, len));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
BufferedInputStream(缓冲字节输入流)

public static void read(File file) {

        try (
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis)
        ) {

            int len;

            // BufferedInputStream本身是不具备读写文件能力
            // 需要借助FileInputStream来读取文件的数据
            while ((len = bis.read()) != -1) {
                System.out.println((char) len);
            }

            // 关闭调用BufferedInputStream.close()实际是调用FileInputStream.close()
            bis.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Writer(字符输出流)
FileWriter(字符输出流)

 public static void write(File file) {
        try (
                FileWriter writer = new FileWriter(file, true)
        ) {
            String str = "Demo write data";

            // 内部维护了一个1024个字符数组的,写数据的时候会先写入它内部维护的字符数组中,
            // 如果需要把数据真正写到硬盘,需要调用flush或者close或者是填满内存的字符数组。
            writer.write(str);
            writer.flush();
            System.out.println("写入成功");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
BufferedWriter(缓冲字符输出流)
public static void write(File file) {
        try (
                FileWriter writer = new FileWriter(file, true);
                BufferedWriter bw = new BufferedWriter(writer);
        ) {
            String str = "Demo write data";

            bw.write(str);
            bw.flush();
            bw.close();
            System.out.println("写入成功");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Reader(字符输入流)

FileReader(字符输入流)

public static void read(File file) {
        try (
                FileReader reader = new FileReader(file);
        ) {

            int len;
            char buf[] = new char[1024];
            while ((len = reader.read(buf)) != -1) {
                System.out.println(new String(buf, 0, len));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
BufferedReader(缓冲字符输入流)

 public static void read(File file) {
        try (
                FileReader reader = new FileReader(file);
                BufferedReader br = new BufferedReader(reader);
        ) {

            String len = null;
            while ((len = br.readLine()) != null) {
                System.out.println(len);
                br.lines();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

InputStreamReader,OutputStreamWriter(转换流)

将字节流转换为字符流

 public static void demo(File file) {
        try (
                FileOutputStream fos = new FileOutputStream(file, true);
                FileInputStream fis = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos))
        ) {
            String str = "Demo write data";
            bw.write(str);
            bw.flush();

            String len;
            while ((len = br.readLine()) != null) {
                System.out.println(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

SequenceInputStream(合并流)

 public static void split() {
        //目标文件
        File goalFile = new File("E:", "Demo/Demo.mp3");
        //结果文件
        File resultFile = new File("E:", "Demo/Split");

        try (
                FileInputStream fis = new FileInputStream(goalFile);
        ) {
            int len;
            byte bur[] = new byte[1024 * 1024];

            for (int i = 1; (len = fis.read(bur)) != -1; i++) {
                FileOutputStream fos = new FileOutputStream(
                        new File(resultFile, "split" + i + ".mp3"));
                fos.write(bur, 0, len);
                fos.flush();
                fos.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   public static void merge() {
        //碎片所在文件夹
        File goalFile = new File("E:", "Demo/Split");
        File[] files = goalFile.listFiles(); //获取文件下所有文件

        Vector<FileInputStream> vector = new Vector<>();
        for (File item : files) {
            //判断是否为MP3格式
            if (item.getName().endsWith(".mp3")) {
                try {
                    vector.add(new FileInputStream(item));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        Enumeration<FileInputStream> elements = vector.elements();
        SequenceInputStream sis = new SequenceInputStream(elements);
        File resultFile = new File("E:", "merge.mp3");

        try (
                FileOutputStream fileOutputStream = new FileOutputStream(resultFile);
        ) {
            byte buf[] = new byte[1024];
            int len;

            while ((len = sis.read(buf)) != -1) {
                fileOutputStream.write(buf, 0, len);
            }
            fileOutputStream.flush();
            sis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

PrintStream(打印流),DataOutputStream(数据流)

PrintStream(打印流)
  • 可以打印任何类型的数据,而且打印数据之前都会先把数据转换成字符串,再进行打印的。
  • 收集异常的日志信息。
 public static void demo() throws FileNotFoundException {
        try (PrintStream printStream = new PrintStream(
                new File("E:", "Demo.txt"))) {

            printStream.println();//通过此函数打印任何数据

        } catch (FileNotFoundException e) {
            PrintStream printStream = new PrintStream(
                    new File("E:", "Demo.txt"));
            e.printStackTrace(printStream); //打印到指定文本
        }
    }
DataOutputStream(数据流)
public static void demo() throws IOException {
        File file = new File("E:/Demo.txt");

        //写入
        DataOutputStream dos = new DataOutputStream(
                new FileOutputStream(file));
        dos.writeUTF("通过Write方法,写入任何数据");

        //读取
        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        String readUTF = dis.readUTF();
        System.out.println("需要对应读取" + readUTF);
    }

内存流

所谓内存流,是将信息暂时存储在内存中。
内存流本身就是内存中的资源,流中的内容也是内存中的资源,理论上是不用关闭流,内存也会将其释放,但是最好还是手动关一下。

public static void demo() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write("Demo".getBytes());

        //从内存中拿出
        byte[] buf = baos.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(buf);
        int len;
        byte resBuf[] = new byte[1024];
        while ((len = bais.read(resBuf)) != -1) {
            System.out.println(new String(resBuf, 0, len));
        }
        bais.close();
    }

PipedInputStream(管道流)

管道流用于线程间的通信

PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
//A线程发送数据给B线程
class AThread extends Thread {

    PipedOutputStream pipedOutput = new PipedOutputStream();

    public PipedOutputStream getPipedOutput() {
        return pipedOutput;
    }

    @Override
    public void run() {

        try {

            for (int i = 65; i < 65 + 26; i++) {
                pipedOutput.write(i);
            }

            pipedOutput.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//B线程接收A发送的数据
class BThread extends Thread {

    PipedInputStream pipedInput;

    //需要将管道流连接才能通信,由此piped的流构造方法允许传入对应管道流
    public BThread(AThread aThread) throws IOException {
        pipedInput = new PipedInputStream(aThread.getPipedOutput());
    }

    @Override
    public void run() {
        int len = 0;
        try {
            while ((len = pipedInput.read()) != -1) {
                System.out.println((char) len);
            }
            pipedInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

IO异常处理
传统方式处理IO异常
public class Run {
    public static void main(String[] args) {

        copy();
    }

    public static void copy() {

        // 目标拷贝文件路径

        File file = new File("D:" + File.separator + "Test.txt");
        // 存放路径
        File file2 = new File("E:" + File.separator + "Test.txt");
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            fileOutputStream = new FileOutputStream(file2);
            int len = 0;
            byte[] bur = new byte[1024];

            while ((len = fileInputStream.read(bur)) != -1) {
                fileOutputStream.write(bur, 0, len);
            }

        } catch (IOException e) {

            // 首先终止代码,然后通知调用者出现问题
            // 把IOException传递给RuntimeException包装一层,让调用者使用更加灵活
            System.out.println("读取资源出错");
            throw new RuntimeException(e);

        } finally {
            try {

                // 关闭资源原则
                // 先开后关
                // 后开先关

                if (fileOutputStream != null) {
                    fileOutputStream.close();
                    System.out.println("关闭输出流资源成功");
                }

            } catch (IOException e) {
                System.out.println("关闭输出流资源出错");
                throw new RuntimeException(e);
            } finally {
                try {
                    if (fileInputStream != null) {
                        fileInputStream.close();
                        System.out.println("关闭输入流资源成功");
                    }
                } catch (IOException e) {
                    System.out.println("关闭输入流资源出错");
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
AutoCloseable处理IO异常

JDK1.7提供了AutoCloseable接口来自动关闭资源,从源码体系上看InputStream实现了Closeable接口,而Closeable接口为AutoCloseable的子类。

public static void demo(){
        try(
                //打开资源代码
            
            ){
            
            //可能出现异常的代码
            //读写操作
            
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static void demo() {
        File file = new File("D:" + File.separator + "Test.txt");
        try (
                
                FileInputStream fileInputStream = new FileInputStream(file);
            
            ) {

            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(buf)) != -1) {
                System.out.println(new String(buf, 0, len));
            }

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

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,490评论 18 139
  • 1 IONo18 1.1IO框架 【 IO:Input Output 在程序运行的过程中,可能需要对一些设备进...
    征程_Journey阅读 937评论 0 1
  • IO流(Input Output) IO技术主要的作用是解决设备与设备之间 的数据传输问题。硬盘 -> 内存内存的...
    奋斗的老王阅读 4,246评论 1 48
  • 第十七天进程和线程-------- 1.进程: 就是正在运行的程序,分配内存让应用程序能够运行。 Windows系...
    枇杷树8824阅读 996评论 0 0
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,110评论 2 34