黑马全套Java教程(九):IO流(上)

简介: 黑马全套Java教程(九):IO流

34 File


34.1 File类概述和构造方法



package myFile;
import java.io.File;
//三个构造方法的使用
public class Demo01 {
    public static void main(String[] args) {
        //1
        File f1 = new File("C:\\Users\\14051\\Desktop\\java_learning\\HelloWorld.java"); //抽象路径表示形式,并不是说这个路径存在
        System.out.println(f1);
        //2
        File f2 = new File("E:\\itcast", "java.txt");
        System.out.println(f2);
        //3
        File f3 = new File("E:\\itcast");
        File f4 = new File(f3, "java.txt");
        System.out.println(f4);
    }
}



34.2 File类创建功能



package myFile;
import java.io.File;
import java.io.IOException;
public class Demo02 {
    public static void main(String[] args) throws IOException {
        //需求1:D盘itcast文件夹下创建文件java.txt
        File f1 = new File("D:\\itcast\\java.txt");
        System.out.println(f1.createNewFile());   //不存在就创建并返回true;存在就不创建,返回false
        //需求2:在itcast文件夹下创建目录
        File f2 = new File("D:\\itcast\\JavaSE");
        System.out.println(f2.mkdir());
        //需求3:创建嵌套子目录
        File f3 = new File("D:\\itcast\\JavaEE\\JavaWeb");
        System.out.println(f3.mkdirs());
        //总结:createNewFile()创建文件,mkdir,mkdirs创建目录
    }
}


34.3 File类判断和获取功能



package myFile;
import java.io.File;
//8个常见方法的使用
public class Demo4 {
    public static void main(String[] args) {
        File f = new File("C:\\programming_software\\JetBrains\\IdeaProjects\\JavaSE_Code\\D34\\src\\myFile\\java.txt");
        //1.是否为文件
        System.out.println(f.isFile());
        //2.是否为目录
        System.out.println(f.isDirectory());
        //3.是否存在
        System.out.println(f.exists());
        //4.获取绝对路径
        System.out.println(f.getAbsolutePath());
        //5.返回路径名字符串
        System.out.println(f.getPath());
        //6.获取文件或目录名称
        System.out.println(f.getName());
        System.out.println("---------------------------");
        //7.获取文件夹下所有文件的字符串
        File f2 = new File("D:\\itcast");
        String[] strArray = f2.list();
        for (String str : strArray) {
            System.out.println(str);
        }
        System.out.println("-----------------------------");
        File[] fileArray = f2.listFiles();   //获取绝对路径
        for (File file : fileArray) {
            System.out.println(file);
        }
        System.out.println("------------------------------");
        for (File file : fileArray) {
//            System.out.println(file.getName());
            if(file.isFile()){
                System.out.println(file.getName());
            }
        }
        System.out.println("-------------------------------");
    }
}



34.4 File类删除功能



package myFile;
import java.io.File;
import java.io.IOException;
//删除功能
public class Demo05 {
    public static void main(String[] args) throws IOException {
        File f1 = new File("java1.txt");  //创建在项目文件下
        System.out.println(f1.createNewFile());
        //删除
        System.out.println(f1.delete());
        //创建和删除目录
        File f2 = new File("itcast");
        System.out.println(f2.mkdir());
        System.out.println(f2.delete());
        System.out.println("----------------------");
        //创建cast目录,接着在目录下创建java.txt文件
        File f3 = new File("cast");
        System.out.println(f3.mkdir());
        File f4 = new File("cast\\java.txt");
        System.out.println(f4.createNewFile());
        System.out.println("----------------------------");
        //再次删除:注意得先删除路径下的内容,才能删除文件夹
        System.out.println(f3.delete());
        System.out.println(f4.delete());
        System.out.println(f3.delete());
    }
}



34.5 递归



package myDIGui;
//递归
public class Demo01 {
    public static void main(String[] args) {
        //不死神兔递归
        int[] arr = new int[20];
        arr[0] = 1;
        arr[1] = 1;
        for (int i = 2; i < arr.length; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }
        System.out.println(arr[19]);  //索引从0开始
        //递归
        System.out.println(f(20));
    }
    //递归实现
    public static int f(int n) {
        if (n == 1 || n == 2) {
            return 1;
        } else {
            return f(n - 1) + f(n - 2);
        }
    }
}



案例一:递归求阶乘




package myDIGui;
//案例:递归求阶乘
public class Demo02 {
    public static void main(String[] args) {
        System.out.println(jiecheng(5));
    }
    public static int jiecheng(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * jiecheng(n - 1);
        }
    }
}


案例二:遍历目录



package myDIGui;
import java.io.File;
//案例:递归目录,只获取文件的绝对路径
public class Demo03 {
    public static void main(String[] args) {
        File f1 = new File("D:\\itcast");
        getAllFilePath(f1);
    }
    public static void getAllFilePath(File srcFile) {
        //获取所有问价或目录的file数组
        File[] fileArray = srcFile.listFiles();
        if (fileArray != null) {   //判断该目录下是否有内容
            for (File file : fileArray) {
                //判断该文件是否为目录
                if (file.isDirectory()) {
                    getAllFilePath(file);
                } else {
                    System.out.println(file.getAbsolutePath());
                }
            }
        }
    }
}



35 字节流


35.1 IO流概述和分类




35.2 字节流写数据



代码:


package myByteStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//将数据写入文件
public class Demo01 {
    public static void main(String[] args) throws IOException {
        //创建字节输出流对象:FileOutputStream
        FileOutputStream fos = new FileOutputStream("fos.txt");  //这一步就能创建文件
        fos.write(97);  //记事本显示a
        fos.write(57);  //字符9
        fos.write(55);  //字符7
        //最后都要释放资源
        fos.close();  //关闭此输出流,并释放与此流相关联的任何系统资源
    }
}



35.3 字节流写数据的3中方式



package myByteStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
//write三个构造方法的使用
public class Demo02 {
    public static void main(String[] args) throws IOException {
//        FileOutputStream fos = new FileOutputStream("fos.txt");
        FileOutputStream fos = new FileOutputStream("fos.txt", true);  //true实现追加写入
        fos.write(97);
        byte[] bys = {98, 99, 100, 101};   //用字节数组,一次性写入多个字节
        fos.write(bys);
        byte[] bys2 = "fghij".getBytes();
        fos.write(bys2);
        byte[] bys3 = "张曼玉".getBytes();
        fos.write(bys3);
        //写入部分字节
        byte[] bys4 = "abcde".getBytes();
        fos.write(bys4, 1, 3);  //索引为1开始写三个,即bcd
        //这一步不要忘掉,释放资源
        fos.close();
    }
}



35.4 字节流写数据的两个小问题


一是怎么换行?


二是怎么追加数据?



package myByteStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
//字节流写数据的两个小问题
public class Demo3 {
    public static void main(String[] args) throws IOException {
        //创建字节输出流对象
        FileOutputStream fos = new FileOutputStream("fos.txt");
//        FileOutputStream fos = new FileOutputStream("fos.txt", true);  //true实现追加写入
        //写数据
        for (int i = 0; i < 10; i++) {
            fos.write("hello".getBytes());
            fos.write("\r\n".getBytes());  //实现换行
        }
        //释放资源
        fos.close();
    }
}


35.5 字节流写数据加异常处理


这个其实就是用try–catch实现,而不用throws抛出异常了。步骤更繁琐,其实没必要


package myByteStream;
import java.io.FileOutputStream;
import java.io.IOException;
//字节流写数据加入异常处理
public class Demo04 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("fos.txt");
            fos.write("hello".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


35.6 字节流读数据(一次读一个字节数据)



package myByteStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//读数据 FileInputStream
public class Demo05 {
    public static void main(String[] args) throws IOException {
        FileInputStream fi = new FileInputStream("fos.txt");
        //第一次读取数据
//        int a = fi.read();
//        System.out.println(a);   //h对应104
//        System.out.println((char) a);  //h
//
//        //第二次
//        System.out.println((char) fi.read());  //没有数据的话会返回-1
//        int by = fi.read();
//        while(by != -1){
//            System.out.print((char)by);
//            by = fi.read();
//        }
        //优化上面代码
        int by;
        while ((by = fi.read()) != -1) {
            System.out.print((char) by);
        }
        fi.close();
    }
}


案例:复制文本文件




package myByteStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//案例:复制文本文件,把文件a的内容读取复制,生成文件b中存储
public class Demo06 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("fos.txt");
        FileOutputStream fos = new FileOutputStream("new_fos.txt");
        //读取,写入
        int by;
        while((by=fis.read())!=-1){
            fos.write(by);
        }
        //释放资源
        fis.close();
        fos.close();
    }
}



35.7 字节流读数据(一次读一个字节数组数据)



package myByteStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Demo07 {
    public static void main(String[] args) throws IOException {
        //创建字节输入流对象
        FileInputStream fis = new FileInputStream("fos.txt");
        byte[] bys = new byte[1024];
        int len;
        while ((len = fis.read(bys)) != -1) {
            System.out.println(new String(bys, 0, len));
        }
        //释放资源
        fis.close();
    }
}



案例:复制图片



package myByteStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//复制图片
public class Demo8 {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("D:\\itcast\\mn.jpg");
        FileOutputStream fos = new FileOutputStream("new_mn.jpg");
        byte[] bys = new byte[1024];
        int len;
        while ((len = fis.read(bys)) != -1) {
            fos.write(bys, 0, len);
        }
        fis.close();
        fos.close();
    }
}


35.8 字节缓冲流



package myByteStream.Demo2;
import java.io.*;
public class Demo01 {
    public static void main(String[] args) throws IOException {
//        FileOutputStream fos = new FileOutputStream("fos.txt");
//        BufferedOutputStream bos = new BufferedOutputStream(fos);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));
        bos.write("hello\r\n".getBytes());
        bos.write("world\r\n".getBytes());
        //释放资源
        bos.close();
        //读数据
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bos.txt"));
//        int by;
//        while ((by = bis.read()) != -1) {
//            System.out.print((char) by);
//        }
        //读数据第二种方式:一次读取一个数组的数据
        byte[] bys = new byte[1024];
        int len;
        while ((len = bis.read(bys)) != -1) {
            System.out.println(new String(bys, 0, len));
        }
        bis.close();
    }
}


案例:复制视频



package myByteStream.Demo2;
import java.io.*;
//复制视频
public class Demo02 {
    public static void main(String[] args) throws IOException {
        //记录开始时间
        long startTime = System.currentTimeMillis();
        //复制视频
//        method1();
//        method2();
//        method3();
        method4();
        //记录结束时间
        long endTime = System.currentTimeMillis();
        System.out.println("共耗时:" + (endTime - startTime) + "毫秒");
    }
    //1.基本字节流一次读写一个字节
    public static void method1() throws IOException {   //共耗时:15031毫秒
        FileInputStream fis = new FileInputStream("D:\\itcast\\视频.mp4");
        FileOutputStream fos = new FileOutputStream("D:\\itcast\\new_视频.mp4");
        int by;
        while ((by = fis.read()) != -1) {
            fos.write(by);
        }
        fos.close();
        fis.close();
    }
    //2.基本字节流一次读写一个字节数组
    public static void method2() throws IOException {  //共耗时:25毫秒
        FileInputStream fis = new FileInputStream("D:\\itcast\\视频.mp4");
        FileOutputStream fos = new FileOutputStream("D:\\itcast\\new_视频.mp4");
        byte[] bys = new byte[1024];
        int len;
        while ((len = fis.read(bys)) != -1) {
            fos.write(bys, 0, len);
        }
        fos.close();
        fis.close();
    }
    //3.字节缓冲流一次读写一个字节
    public static void method3() throws IOException {   //共耗时:77毫秒
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\itcast\\视频.mp4"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\itcast\\new_视频.mp4"));
        int by;
        while ((by = bis.read()) != -1) {
            bos.write(by);
        }
        bis.close();
        bos.close();
    }
    //4.字节缓冲流一次读写一个字节数组
    public static void method4() throws IOException {  //共耗时:7毫秒
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\itcast\\视频.mp4"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\itcast\\new_视频.mp4"));
        byte[] bys = new byte[1024];
        int len;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys, 0, len);
        }
        bos.close();
        bis.close();
    }
}


36 字符流


36.1 为什么会出现字符流



package myCharStream.Demo1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/*
    一个汉字存储:
        如果是GBK编码,占用2个字节
        如果是UTF-8编码,占用3个字节
 */
public class Demo01 {
    public static void main(String[] args) throws IOException {
//        FileInputStream fis = new FileInputStream("fos.txt");
//
//        int by;
//        while ((by = fis.read()) != -1) {
//            System.out.print((char) by);
//        }
//
//        fis.close();
        String s = "中国";
        byte[] bys = s.getBytes("UTF-8");
        System.out.println(Arrays.toString(bys));
        byte[] bys2 = s.getBytes("GBK");
        System.out.println(Arrays.toString(bys2));
    }
}


36.2 编码表







36.3 字符串中的编码解码问题



package myCharStream.Demo1;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class Demo02 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //定义一个字符串
        String s = "中国";
        byte[] bys = s.getBytes("GBK");       //编码
        System.out.println(Arrays.toString(bys));
        String ss = new String(bys, "GBK");   //解码
        System.out.println(ss);
    }
}


36.4 字符流中的编码解码问题



package myCharStream.Demo2;
import java.io.*;
//字节流读取数据
public class Demo01 {
    public static void main(String[] args) throws IOException {
//        FileOutputStream fos = new FileOutputStream("osw.txt");
//        OutputStreamWriter osw = new OutputStreamWriter(fos);
//        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"));
//        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"), "UTF-8");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw.txt"), "GBK");
        osw.write("中国");
        osw.close();
        //读数据
        InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"),"GBK");
        //一次读取一个字符数据
        int ch;
        while((ch=isr.read())!=-1){
            System.out.print((char) ch);
        }
        isr.close();
    }
}


目录
相关文章
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
518 1
|
Oracle Java 关系型数据库
Java 简单教程
Java是跨平台、面向对象的编程语言,广泛用于企业开发、Android应用等。本教程涵盖环境搭建、基础语法、流程控制、面向对象、集合与异常处理,助你快速入门并编写简单程序,为进一步深入学习打下坚实基础。
812 0
|
安全 Java
Java之泛型使用教程
Java之泛型使用教程
585 10
|
Java 测试技术 API
Java IO流(二):文件操作与NIO入门
本文详解Java NIO与传统IO的区别与优势,涵盖Path、Files类、Channel、Buffer、Selector等核心概念,深入讲解文件操作、目录遍历、NIO实战及性能优化技巧,适合处理大文件与高并发场景,助力高效IO编程与面试准备。
|
SQL Java 数据库连接
Java IO流(一):字节流与字符流基础
本文全面解析Java IO流,涵盖字节流、字符流及其使用场景,帮助开发者理解IO流分类与用途,掌握文件读写、编码转换、异常处理等核心技术,通过实战案例提升IO编程能力。
|
Java 关系型数据库 数据库
Java 项目实战教程从基础到进阶实战案例分析详解
本文介绍了多个Java项目实战案例,涵盖企业级管理系统、电商平台、在线书店及新手小项目,结合Spring Boot、Spring Cloud、MyBatis等主流技术,通过实际应用场景帮助开发者掌握Java项目开发的核心技能,适合从基础到进阶的学习与实践。
1788 4
|
存储 Java Linux
操作系统层面视角下 Java IO 的演进路径及核心技术变革解析
本文从操作系统层面深入解析Java IO的演进历程,涵盖BIO、NIO、多路复用器及Netty等核心技术。分析各阶段IO模型的原理、优缺点及系统调用机制,探讨Java如何通过底层优化提升并发性能与数据处理效率,全面呈现IO技术的变革路径与发展趋势。
357 3
|
监控 Java API
现代 Java IO 高性能实践从原理到落地的高效实现路径与实战指南
本文深入解析现代Java高性能IO实践,涵盖异步非阻塞IO、操作系统优化、大文件处理、响应式网络编程与数据库访问,结合Netty、Reactor等技术落地高并发应用,助力构建高效可扩展的IO系统。
564 0
|
缓存 安全 Java
Java 并发新特性实战教程之核心特性详解与项目实战
本教程深入解析Java 8至Java 19并发编程新特性,涵盖CompletableFuture异步编程、StampedLock读写锁、Flow API响应式流、VarHandle内存访问及结构化并发等核心技术。结合电商订单处理、缓存系统、实时数据流、高性能计数器与用户资料聚合等实战案例,帮助开发者高效构建高并发、低延迟、易维护的Java应用。适合中高级Java开发者提升并发编程能力。
764 0
|
Oracle Java 关系型数据库
java 编程基础入门级超级完整版教程详解
这份文档是针对Java编程入门学习者的超级完整版教程,涵盖了从环境搭建到实际项目应用的全方位内容。首先介绍了Java的基本概念与开发环境配置方法,随后深入讲解了基础语法、控制流程、面向对象编程的核心思想,并配以具体代码示例。接着探讨了常用类库与API的应用,如字符串操作、集合框架及文件处理等。最后通过一个学生成绩管理系统的实例,帮助读者将理论知识应用于实践。此外,还提供了进阶学习建议,引导学员逐步掌握更复杂的Java技术。适合初学者系统性学习Java编程。资源地址:[点击访问](https://pan.quark.cn/s/14fcf913bae6)。
1463 2