8、IO_1

File

  • 常用构造
File(String pathname)  目录路径/文件路径
File(String parent, String child) == File(File parent, String child) 
    parent: 父级目录   child: 子级文件名称
  • 操作文件
1. boolean exists()  判断文件/目录是否存在
2. String getName() 获得文件或者目录名称
3. boolean createNewFile()   创建文件
4. long length()   获得文件内容大小
5. boolean delete() 删除文件
6. boolean isFile()  判断是否是文件  
  • 操作目录
1. boolean mkdir()  
2. boolean mkdirs()
3. String[] list() 获得当前目录下的子目录和子文件名称
4. File[] listFiles()  获得当前目录下的子目录和子文件
  • 递归(遍历当前路径下的所有文件)
  private static void demo4(File file,String string) {
        //获得指定目录下的所有的子目录和子文件
        Objects.requireNonNull(file);
        if(!file.exists()){
            System.out.println("当前路径不存在");
            return;
        }

        // String[] list()
        String[] fileNames = file.list();//获得1级子目录和子文件
//        System.out.println(Arrays.toString(fileNames));

        for (String str:fileNames){
            //结合str创建File对象
            File child = new File(file, str);
            //判断child是目录还是一个文件
            if(child.isDirectory()){
                //获得子目录下的文件   递归: 自己调用自己的逻辑  (避免出现死循环)
                System.out.println(string+str);
                demo4(child,"| "+string);
            }else{
                System.out.println(string+str);
            }
        }
    }
 private static void demo5(File file, String s) {
        File[] files = file.listFiles();
        for (File fi:files){
            if(fi.isDirectory()){
                System.out.println(s+fi.getName());
                demo5(fi,"| "+s);
            }else{
                System.out.println(s+fi.getName());
            }
        }
    }
  • 文件过滤
File[] listFiles(FileFilter filter)  
File[] listFiles(FilenameFilter filter)  
    private static void demo7(File file, String s) {
        //查看文件扩展名是 *.java
        //FilenameFilter
//        File[] files = file.listFiles(new FilenameFilter() {
//            @Override
//            public boolean accept(File dir, String name) {// dir 父级目录  name: 文件/目录名称
//                //当前name是否是文件名称
//                //如果name是目录名称的话  需要直接放行
//                if(new File(dir,name).isDirectory()){
//                    return true;
//                }
//                return name.endsWith("java");
//            }
//        });

        File[] files = file.listFiles((parent, name)->{  // FilenameFilter
            if(new File(parent,name).isDirectory()){
                return true;
            }
            return name.endsWith("java");
        });
   }
	//FileFilter
        File[] files = file.listFiles(child->{
            if(child.isDirectory()){
                return true;
            }
            return child.getName().endsWith("java");
        });

IO_字节流

  • 读入写出
  • 在计算机里面,所有的文件都是二进制的文件, 操作文件内容都是通过字节。图片 文本 音频 压缩 都是以字节进行存储的, 字节流可以操作计算机里面任意类型的文件。
  • 字节输入流——InputStream
    • 常用子类:FileInputStream BufferedInputStream DataInputStream ObjectInputStream
public abstract class InputStream extends Object implements Closeable
   
int available()  获得当前输入流对象有效的字节数  ===> file.length()
void close()   关闭流
    
abstract int read()  一次一个字节进行读取  读到末尾 -1  
int read(byte[] b)  一次读取b.length个字节  存储到byte[]   返回值读到的有效字节个数  -1    
int read(byte[] b, int off, int len)  off:从指定byte[]索引位置写入
 一次读取len个字节 存到byte[] 数组中   返回值读到的有效字节个数  -1   

效率高低;
  读取文件大小内容一定的: 100个字节
     read() 读取100次 打印100read(byte[50])  读了100次  打印2次   适合大文件的读取
FileInputStream(File file) 
FileInputStream(String name) 
    // 读取文件内容
    private static void demo2(String path) {
        //jdk1.7+ 更加优雅的方式关闭流对象  try...with...resources(前提: 类必须实现Closeable) ==> 自动关闭流对象

        try (
                //1.创建流对象
                InputStream inputStream = new FileInputStream(path);
        ) {

            //2.循环读取文件内容
            byte[] bytes = new byte[1024];//空间大小 1024的整数倍
//            int len = inputStream.read(bytes);// 一次读取1024个字节  文件内容 存储到了bytes

//            for(byte by:bytes){
//                System.out.print((char)by);
//            }
            //字节数组转换成String
//            System.out.println(new String(bytes));//解码操作 与编码格式有关

            int content = 0;
            while ((content = inputStream.read(bytes)) != -1) {// <=1024
                System.out.println(new String(bytes, 0, content));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
  • 字节输出流——OutputStream(若目标文件不存在,输出流会自动创建目标文件)
public abstract class OutputStream extends Object implements Closeable, Flushable
  
void close()  
void write(byte[] b)   一次写b.length个字节
void write(byte[] b, int off, int len)  
void write(int b)  一次写一个字节内容
 
FileOutputStream(String name)
FileOutputStream(String name, boolean append) append: 是否会在末尾追加文本数据 默认:false
public class OutPutStreamDemo {

    public static void main(String[] args) {
        demo1();
    }

    /**
     * 测试字节输入流: 将数据写入指定文件中
     */
    private static void demo1() {

        try (
                //1.创建输出流对象  文件可以自动创建
                OutputStream outputStream = new FileOutputStream("a.txt",false)
        ) {

            //2.写入数据 write(int i)
//            outputStream.write('a');//字符的ASCII
//            outputStream.write(97);
//            outputStream.write('\n');
//            outputStream.write('我');// 一次写一个字节 utf-8 3个字节

            //2.写入数据  write(byte[] by)
//            byte[] bytes = {'a','b',97,98};
//            outputStream.write(bytes);
            //2.写入数据  write(byte[] by, int off,int len) off: index   len: 字节个数

            byte[] bytes = "我们在学习".getBytes();
            outputStream.write(bytes,0,bytes.length);

            System.out.println("写入完毕。。。。。。。");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 高效字节流
高效字节流: 自带一个缓冲区  byte[] buf= 8192
BufferedInputStream
BufferedOutPutStream
    BufferedInputStream(InputStream in) 
    BufferedOutputStream(OutputStream out) 

IO_字符流

  • 字符流 = 字节流+编码 (GBK UTF-8) ,只能针对于文本文件(txt、 java)
  • 字符输入流——Reader
    • 常用子类: FileReder BufferedReader InputStreamReader
public class ReaderDemo {

    public static void main(String[] args) {
        demo3();
    }

    private static void demo3() {
        try(
                //1.创建字符输入流对象
                Reader reader = new FileReader("D:\\idea_workspace\\one\\day15\\src\\com\\javasm\\io\\InputStreamDemo.java");
        ){
            //2.循环读取文件内容
            char[] chars = new char[1024];
            int len = 0;
            while ((len=reader.read(chars,0,chars.length))!=-1){//有效的字符个数
                //将字符数组转换成 字符串
                System.out.println(new String(chars,0,len));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    private static void demo2() {
        try(
                //1.创建字符输入流对象
                Reader reader = new FileReader("D:\\idea_workspace\\one\\day15\\src\\com\\javasm\\io\\InputStreamDemo.java");
        ){
            //2.循环读取文件内容
            char[] chars = new char[1024];
            int len = 0;
            while ((len=reader.read(chars))!=-1){
                //将字符数组转换成 字符串
                System.out.println(new String(chars));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 测试: read()  一次读取一个字符
     */
    private static void demo1() {
        try(
                //1.创建字符输入流对象
                Reader reader = new FileReader("D:\\idea_workspace\\one\\day15\\src\\com\\javasm\\io\\InputStreamDemo.java");
                ){
            //2.循环读取文件内容
            int len = 0;
            while ((len=reader.read())!=-1){
                System.out.print((char)len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
  • 字符输出流——Writer
public abstract class Writer
extends Object
implements Appendable, Closeable, Flushable
    
    void write(char[] cbuf)  
     void write(char[] cbuf, int off, int len)  
    void write(String str)  
    void write(int c)  
    
    Writer append(CharSequence csq)  
    
    FileWriter(String fileName)
    FileWriter(String fileName, boolean append) false
public class WriterDemo {
    public static void main(String[] args) {
        try(
                //1.创建字符输出流对象
                Writer writer = new FileWriter("b.txt",true)
                ){
            //2.将数据写入文件
            writer.write('a');
            writer.write('\n');
            writer.write("我们".toCharArray());
            writer.write("在学习java");
            writer.append("水果为单位dhdgs");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

文件上传下载

public class FileUtil {
    private FileUtil() {
    }

    /**
     * 使用高效字符流实现文件复制
     * @param sourceFile
     * @param targetFile
     */
    public static void copyFile4(String sourceFile, String targetFile) {
        try (
                BufferedReader bufferedReader = new BufferedReader(new FileReader(sourceFile));
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(targetFile));
        ) {
            String content = "";
            while ((content = bufferedReader.readLine()) != null) {
                bufferedWriter.write(content);
                bufferedWriter.newLine();
            }
            System.out.println("success");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用字符流完成
     *
     * @param sourceFile
     * @param targetFile
     */
    public static void copyFile3(String sourceFile, String targetFile) {
        try (
                Reader reader = new FileReader(sourceFile);
                Writer writer = new FileWriter(targetFile);
        ) {

            char[] chars = new char[1024];
            int len = 0;
            while ((len = reader.read(chars)) != -1) {//有效的字符个数
                writer.write(chars, 0, len);
            }
            System.out.println("success");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void copyFile2(String sourceFile, String targetFile) {
        try (
                //1.创建高效字节输入输出流对象
                BufferedInputStream bufferedInputStream = new BufferedInputStream(new URL(sourceFile).openStream());
                BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
        ) {
            int len = 0;
            byte[] by = new byte[1024];//存储到buf
            while ((len = bufferedInputStream.read(by)) != -1) {
                outputStream.write(by, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void copyFile1(String sourceFile, String targetFile) {
        try (
                //1.创建输入流对象
                InputStream inputStream = new FileInputStream(sourceFile);
                //创建输出流对象
                OutputStream outputStream = new FileOutputStream(targetFile);
        ) {
            //2.读取文件sourceFile内容

            byte[] bytes = new byte[1024 * 10];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                //3.读到的数据写入targetFile
                outputStream.write(bytes, 0, len);
            }
            System.out.println("文件复制成功。。。。。");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param sourceFile 源文件路径
     * @param targetFile 目标文件路径
     */
    public static void copyFile(String sourceFile, String targetFile) {
        try (
                //1.创建输入流对象
                InputStream inputStream = new FileInputStream(sourceFile);
                //创建输出流对象
                OutputStream outputStream = new FileOutputStream(targetFile);
        ) {
            //2.读取文件sourceFile内容
            int len = 0;
            while ((len = inputStream.read()) != -1) {
                //3.读到的数据写入targetFile
                outputStream.write(len);

            }
            System.out.println("文件复制成功。。。。。");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值