Java:IO技术

2023-05-21  本文已影响0人  iOS_修心

IO流概述

一.File类

1.File类介绍

2.File类的构造方法

方法名 说明
File(String pathname) 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
File(String parent, String child) 从父路径名字符串和子路径名字符串创建新的 File实例
File(File parent, String child) 从父抽象路径名和子路径名字符串创建新的 File实例
//File(String pathname): 通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例
File f1 = new File("/Users/Downloads/File");
System.out.println(f1);

//File(String parent, String child): 从父路径名字符串和子路径名字符串创建新的 File实例
File f2 = new File("/Users/Downloads/File","java.txt");
System.out.println(f2);

//File(File parent, String child): 从父抽象路径名和子路径名字符串创建新的 File实例
File f3 = new File("/Users/Downloads/File");
File f4 = new File(f3,"java.txt");
System.out.println(f4);

3.File类创建和删除

//1.创建文件
File f1 = new File("/Users/Downloads/File/java.txt");
System.out.println(f1.createNewFile());
System.out.println("--------");

//2.创建一个目录JavaSE
File f2 = new File("/Users/Downloads/File/JavaSE");
System.out.println(f2.mkdir());
System.out.println("--------");

//3.创建一个多级目录JavaWEB\\HTML
File f3 = new File("/Users/Downloads/File/HTML/1");
System.out.println(f3.mkdirs());
System.out.println("--------");

//4:删除目录下的文件或文件夹
File f4 = new File("/Users/Downloads/File/JavaSE");
System.out.println(f2.delete());

4.File类判断和获取

//创建一个File对象
File f = new File("filepro");

// public boolean isDirectory():测试此抽象路径名表示的File是否为目录
// public boolean isFile():测试此抽象路径名表示的File是否为文件
// public boolean exists():测试此抽象路径名表示的File是否存在
System.out.println(f.isDirectory());
System.out.println(f.isFile());
System.out.println(f.exists());

//public String getAbsolutePath():返回此抽象路径名的绝对路径名字符串
//public String getPath():将此抽象路径名转换为路径名字符串
//public String getName():返回由此抽象路径名表示的文件或目录的名称
System.out.println(f.getAbsolutePath());
System.out.println(f.getPath());
System.out.println(f.getName());
System.out.println("--------");

// public File[] listFiles():返回此抽象路径名表示的目录中的文件和目录的File对象数组
File f2 = new File("filepro");
File[] fileArray = f2.listFiles();
for(File file : fileArray) {
    System.out.println(file);
}

5.实例

删除一个多级文件夹
    public static void main(String[] args) {
        //delete方法,只能删除文件和空文件夹.
        //如果现在要删除一个有内容的文件夹?
        //先删掉这个文件夹里面所有的内容.最后再删除这个文件夹
        File src = new File("filepro");
        deleteDir(src);
    }
    
    //1.定义一个方法,接收一个File对象
    private static void deleteDir(File src) {
        //先删掉这个文件夹里面所有的内容.
        //递归 方法在方法体中自己调用自己.
        //注意: 可以解决所有文件夹和递归相结合的题目
        //2.遍历这个File对象,获取它下边的每个文件和文件夹对象
        File[] files = src.listFiles();
        //3.判断当前遍历到的File对象是文件还是文件夹
        for (File file : files) {
            //4.如果是文件,直接删除
            if(file.isFile()){
                file.delete();
            }else{
                //5.如果是文件夹,递归调用自己,将当前遍历到的File对象当做参数传递
                deleteDir(file);//参数一定要是src文件夹里面的文件夹File对象
            }
        }
        //6.参数传递过来的文件夹File对象已经处理完成,最后直接删除这个空文件夹
        src.delete();
    }
    
统计一个文件夹中每种文件的个数并打印
public static void main(String[] args) {
    //统计一个文件夹中,每种文件出现的次数.
    //统计 --- 定义一个变量用来统计. ---- 弊端:同时只能统计一种文件
    //利用map集合进行数据统计,键 --- 文件后缀名  值 ----  次数

    File file = new File("/File项目");
    HashMap<String, Integer> hm = new HashMap<>();
    getCount(hm, file);
    System.out.println(hm);
}

//1.定义一个方法,参数是HashMap集合用来统计次数和File对象要统计的文件夹
private static void getCount(HashMap<String, Integer> hm, File file) {
    //2.遍历File对象,获取它下边的每一个文件和文件夹对象
    File[] files = file.listFiles();
    for (File f : files) {
        //3.判断当前File对象是文件还是文件夹
        if(f.isFile()){
            //如果是文件,判断这种类型文件后缀名在HashMap集合中是否出现过
            String fileName = f.getName();
            String[] fileNameArr = fileName.split("\\.");
            if(fileNameArr.length == 2){
                String fileEndName = fileNameArr[1];
                if(hm.containsKey(fileEndName)){
                    //出现过,获取这种类型文件的后缀名出现的次数,对其+1,在存回集合中
                    Integer count = hm.get(fileEndName);
                    //这种文件又出现了一次.
                    count++;
                    //把已经出现的次数给覆盖掉.
                    hm.put(fileEndName,count);
                }else{
                    // 没出现过,将这种类型文件的后缀名存入集合中,次数存1
                    hm.put(fileEndName,1);
                }
            }
        }else{
            //如果是文件夹,递归调用自己,HashMap集合就是参数集合,File对象是当前文件夹对象代码实现
            getCount(hm,f);
        }
    }
}

二.字节流

1.字节输出流
static void test() throws IOException {
    //1.创建字节输出流的对象
    // 注意点:如果文件不存在,会帮我们自动创建出来.
    // 如果文件存在,会把文件清空.
    FileOutputStream fos = new FileOutputStream("a.txt");

    //2,写数据     
    // 传递一个整数时,那么实际上写到文件中的,是这个整数在码表中对应的那个字符.
    fos.write(98);
    //添加换行符一个换行
    fos.write("\r\n".getBytes());
    // 添加中文,需要进行转码
    fos.write("哈哈".getBytes());
    // 添加数组
    byte [] bys = {97,98,99,100,101,102,103};
    fos.write(bys,0,4);

    //3,释放资源
    fos.close(); //告诉操作系统,我现在已经不要再用这个文件了.
}
static void test1(){
    FileOutputStream fos = null;
    try {
        //System.out.println(2/0);
        fos = new FileOutputStream("a.txt");
        fos.write(97);
    }catch(IOException e){
        e.printStackTrace();
    }finally {
        //finally语句里面的代码,一定会被执行.
        if(fos != null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.字节输入流

static void test2() throws IOException {
    //如果文件存在,那么就不会报错.
    //如果文件不存在,那么就直接报错.
    FileInputStream fis = new FileInputStream("a.txt");

    //一次读取一个字节,返回值就是本次读到的那个字节数据.
    //也就是字符在码表中对应的那个数字.
    //如果我们想要看到的是字符数据,那么一定要强转成char
    int read = fis.read();
    System.out.println((char)read);

    //读多个字节,每调用一次就读取一个字节
    int b;
    while ((b = fis.read())!=-1){
        System.out.println((char) b);
    }

    //释放资源
    fis.close();
}

3.字节读写数据

static void test3() throws IOException {
  //1 创建了字节输入流,准备读数据.
  FileInputStream fis = new FileInputStream("a.avi");
  //创建了字节输出流,准备写数据.
  FileOutputStream fos = new FileOutputStream("b.avi");

  //一次读写一个字节
  int b;
  while((b = fis.read())!=-1){
      fos.write(b);
  }
  // 3.释放资源
  fis.close();
  fos.close();
}
static void test4() throws IOException {
    FileInputStream fis = new FileInputStream("a.avi");
    FileOutputStream fos = new FileOutputStream("c.avi");

    // //一次读写一个字节数组
    byte [] bytes = new byte[1024];
    int len; //本次读到的有效字节个数 -- 这次读了几个字节.
    while((len = fis.read(bytes))!=-1){
        fos.write(bytes,0,len);
    }

    fis.close();
    fos.close();
}

4.字节缓冲流读写

public static void method6() throws IOException {
   //字节缓冲流一次读写一个字节
   BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.avi"));
   BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.avi"));

   int by;
   while ((by=bis.read())!=-1) {
       bos.write(by);
   }

   bos.close();
   bis.close();
}
static void test5() throws IOException{
   //字节缓冲流一次读写一个字节数组
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.avi"));
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.avi"));

    byte[] bys = new byte[1024];
    int len;
    while ((len=bis.read(bys))!=-1) {
        bos.write(bys,0,len);
    }

    bos.close();
    bis.close();
}

三.字符流

1为什么会出现字符流

2.编码表

3.字符串中的编码解码

方法名 说明
byte[] getBytes() 使用平台的默认字符集将该 String编码为一系列字节
byte[] getBytes(String charsetName) 使用指定的字符集将该 String编码为一系列字节
String(byte[] bytes) 使用平台的默认字符集解码指定的字节数组来创建字符串
String(byte[] bytes, String charsetName) 通过指定的字符集解码指定的字节数组来创建字符串
static void method1() throws UnsupportedEncodingException {
    String str = "中文编码";

    //利用idea默认的UTF-8将中文编码为一系列的字节
    byte[] bytes1 = str.getBytes();
    System.out.println(Arrays.toString(bytes1));
    //利用默认的UTF-8进行解码
    String s1 = new String(bytes1);
    System.out.println(s1);

    // 指定编码类型:GBK
    byte[] bytes2 = str.getBytes("GBK");
    System.out.println(Arrays.toString(bytes2));
    //利用指定的GBK进行解码
    String s2 = new String(bytes2,"GBK");
    System.out.println(s2);
}
[-28, -72, -83, -26, -106, -121, -25, -68, -106, -25, -96, -127]
中文编码
[-42, -48, -50, -60, -79, -32, -62, -21]
中文编码

4.字符流写数据

static void test1() throws IOException {
    //创建字符输出流的对象
    FileWriter fw = new FileWriter("a.txt");

    // 写一个字符
    fw.write(97);
    fw.write("\n\r");
    // 写出一个字符数组
    char [] chars = {97,98,99,100,101};
    fw.write(chars);
    // 写出字符数组的一部分
    fw.write(chars,0,3);
    // 写一个字符串
    String line = "输出流的对象123-abc";
    fw.write(line);
    fw.write(line,0,2);

    //释放资源
    fw.close();
}

5.字符流读数据

static void test2() throws IOException {
    //创建字符输入流的对象
    FileReader fr = new FileReader("a.txt");
    //一次读取一个字符
    int ch;
    while((ch = fr.read()) != -1){
        System.out.println((char) ch);
    }
    //释放资源
    fr.close();
}
static void test3() throws IOException {
    FileReader fr = new FileReader("a.txt");

    char [] chars = new char[1024];
    int len;
    //read方法还是读取,但是一次读取多个字符
    //他把读到的字符都存入到chars数组。
    //返回值:表示本次读到了多少个字符。
    while((len = fr.read(chars))!=-1){
        System.out.println(new String(chars,0,len));
    }

    fr.close();
}

6.缓冲字符流

方法名 说明
BufferedWriter(Writer out) 创建字符缓冲输出流对象
BufferedReader(Reader in) 创建字符缓冲输入流对象
void newLine() 写一行行分隔符,行分隔符字符串由系统属性定义
String readLine() 读一行文字。 如果已经到达结尾,则为null
static void test4() throws IOException {
    //字符缓冲输入
    BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
    //写出数据
    bw.write("字符缓冲");
    //跨平台的回车换行
    bw.newLine();
    //释放资源
    bw.close();

    //字符缓冲输出
    BufferedReader br = new BufferedReader(new FileReader("a.txt"));
    //使用循环来进行改进
    String line;
    //可以读取一整行数据。一直读,读到回车换行为止。
    //但是他不会读取回车换行符。
    while((line = br.readLine()) != null){
        System.out.println(line);
    }
    //释放资源
    br.close();
}

四.转换流

1.概述

2. 构造方法

方法名 说明
InputStreamReader(InputStream in) 使用默认字符编码创建InputStreamReader对象
InputStreamReader(InputStream in,String chatset) 使用指定的字符编码创建InputStreamReader对象
OutputStreamWriter(OutputStream out) 使用默认字符编码创建OutputStreamWriter对象
OutputStreamWriter(OutputStream out,String charset) 使用指定的字符编码创建OutputStreamWriter对象
static void test1() throws IOException {
    //从字符流到字节流
    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();
}
上一篇 下一篇

猜你喜欢

热点阅读