文件和IO

本文详细介绍了Java中的File类及其操作,包括文件查找、字节流(如OutputStream、InputStream)与字符流(如Writer、Reader)的概念、使用示例,以及缓冲流(BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter)的优化,以及打印流(PrintStream、PrintWriter)的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

File类

File类是文件和目录路径名的抽象表示形式
File类可以实现文件的创建、删除、重命名、得到路径、创建时间等等,是唯一与文件本身有关的操作类

查找文件
package com.ty.IODemo;

import java.io.File;

public class FIleDemo2 {
    public static void main(String[] args){
        findFile(new File("D:\\software\\JavaCode"),".jpg");
    }
    private static void findFile(File target, String etx){
        if (target == null) return;
        if (target.isDirectory()){ //查看文件是否存在
            File[] files = target.listFiles();
            if (files != null){
                for (File f : files) {
                    findFile(f,etx); // 递归调用
                }
            }
        }else {
            String with = target.getName().toLowerCase();
            if (with.endsWith(etx)){
                System.out.println(target.getAbsolutePath());
            }
        }
    }
}

字节流

IO流

输入输出流(Input\Output)
流是一组有顺序的,有起点和终点的字节集合,对数据传输的总称或抽象,就是数据在两设备间的传输
本质就是数据传输,根据数据传输特性将流抽象为各种类,方便更直观地进行数据操作
IO分类:
处理数据类型不同:字符流、字节流
数据流向不同:输入流、输出流
字节是数据传输的基本单位,文件内容也是以字节为单位存储的,从文件中把数据读到程序使用输入流,从程序中把数据写到文件中使用输出流

字节输出流 OutputStream

输出字节流的超类,输出流接受输出字节并将这些字节发送到InputStream类某个接收器要向文件中输出,使用FileOutputStream

字节输入流 InputStream

表示字节输入流的所有类的超类,FileInputStream从文件系统中的某个文件中获得输入字节

字符流

Writer

写入字符流的抽象类,子列必须实现Writer()方法,多子类重写和OutputStream一样,对文件的操作使用,FileWriter类完成

Reader

用于读取字符流的抽象类,子类必须实现的方法read(),多数子类将重写和InputStream,使用FileReader进行实例化操作。
输入输出流操作原理每次只会操作一个字节(从文件中读取或者写入)
字节操作流,默认每次执行写入操作直接把数据写入文件

字节流和字符流的区别

一般操作非文本文件时,使用字节流,操作文本文件时,建议使用字符流

copy文件 边读边写

package com.ty.IODemo;

import java.io.*;

public class copyReaderWriter {
    public static void main(String[] args) {
        copy("E:\\3毕业设计作品\\sister.jpg","E:\\3毕业设计作品\\java\\sister.jpg");
        System.out.println("copy Success!!!");
    }

    private static void copy(String src, String target) {
        File srcFile = new File(src);
        File targetFile = new File(target);
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = new FileInputStream(srcFile);
            outputStream = new FileOutputStream(targetFile);
            StringBuilder stringBuilder = new StringBuilder();
            byte[] bytes = new byte[1];
            int len = -1;
            while ((len = inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream!= null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

字节字符转化流

转换流可以将一个字节流转换为字符流,反之,也可以
OutputStreamWriter:可以将输出的字符流转换为字节流的输出形式
InputStreamReader:将输入的字节流转换为字符流输入形式

package com.ty.IODemo;

import java.io.*;
import java.nio.charset.Charset;

public class ChangeStreamDemo {
    public static void main(String[] args) throws FileNotFoundException {
       // FileInputStream fileInputStream = new FileInputStream("E:\\3毕业设计作品\\java\\test.txt");
        //readerStreamDemo(fileInputStream);


        FileOutputStream fileOutputStream = new FileOutputStream("E:\\3毕业设计作品\\java\\test.txt",true);
        writerStreamWriter(fileOutputStream);
    }

    private static void readerStreamDemo(InputStream inputStream) {
        Reader reader = new InputStreamReader(inputStream, Charset.defaultCharset());
        char[] chars = new char[1024];
        int len = -1;
        try {
            while ((len = reader.read(chars)) != -1){
                System.out.println(new String(chars,0,len));
            }
            System.out.println("reader success!!!");
            reader.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writerStreamWriter(OutputStream outputStream){
        Writer writer = new OutputStreamWriter(outputStream, Charset.defaultCharset());
        try {
            writer.write("恭喜,写入成功  !!!\r\n");
            System.out.println("writer Success!!!");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

缓冲流

对文件或其他目标频繁的读写操作,效率低,性能差
好处是能够更加搞笑的读写信息,原理是将数据先缓冲起来,然后一起写入或者读取
BufferedInputStream:为另一个输入流添加一些功能,在创建时,会创建一个内部缓冲区数组,用于缓冲数据
BufferedOutputStream通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必针对每次字节写入调用底层系统
BufferedReader:从字符输出流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取
BufferedWriter:将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入

package com.ty.IODemo;

import java.io.*;

public class BufferedStreamDemo {
    public static void main(String[] args) {
        //buffer();
        //bufferReader();
        //charReader();
        charWriter();
    }
    private static void buffer(){
        File file = new File("E:\\3毕业设计作品\\java\\test.txt");
        try {
            OutputStream fileOutputStream = new FileOutputStream(file, true);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            String info = "这个就是缓冲流!!!\r\n";
            fileOutputStream.write(info.getBytes());
            System.out.println("buffered Success !!!");
            bufferedOutputStream.close();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void bufferReader(){
        File file = new File("E:\\3毕业设计作品\\java\\test.txt");
        try {
            InputStream inputStream = new FileInputStream(file);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = bufferedInputStream.read(bytes)) != -1){
                System.out.println(new String(bytes,0,len));
            }
           // System.out.println(new String(bytes,0,len));
            //System.out.println(bufferedInputStream.read(bytes,0,len));
            System.out.println("缓冲 读取成功!!!");
            bufferedInputStream.close();
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void charReader(){
        File file = new File("E:\\3毕业设计作品\\java\\test.txt");
        try {
            FileReader fileReader = new FileReader(file);
            BufferedReader br = new BufferedReader(fileReader);
            char[] chars = new char[1024];
            int len = -1;
            while ((len = br.read(chars)) != -1){
                System.out.println(new String(chars,0,len));
            }
            br.close();
            System.out.println("字符 读取成功 @@@");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void charWriter(){
        File file = new File("E:\\3毕业设计作品\\java\\test.txt");
        try {
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("charWriter Success!!!");
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedReader:默认缓冲大小为8k,但可以手动指定内存大小,把数据读取到缓存中,减少每次转换过程,效率更高,BufferedWriter也是一样的。

打印流

用于输出。
字节打印流:PrintStream
字符打印流:PrintWriter
打印流可以很方便的进行输出

package com.ty.IODemo;

import java.io.*;

public class PrintStreamWriterDemo {
    public static void main(String[] args) {
        //bytePrint();
        charWriter();
    }
    public static void bytePrint(){
        File file = new File("E:\\3毕业设计作品\\java\\test.txt");
        try {
            OutputStream out = new FileOutputStream(file);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
            PrintStream printStream = new PrintStream(bufferedOutputStream);
            printStream.println("字节打印流!!!");
            System.out.println("====================");
            printStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void charWriter(){
        File file = new File("E:\\3毕业设计作品\\java\\test.txt");
        try {
            Writer writer = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(writer);
            PrintWriter pw = new PrintWriter(bw);
            pw.println("字符打印流");
            pw.close();
            System.out.println("----------");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值