Java File使用 / IO流

本文详细介绍了Java中的File类基本操作,如文件信息获取、移动与删除,多级文件夹搜索,字符集编码解码,以及IO流(字节流与字符流)、文件拷贝和资源释放的最佳实践。同时涵盖了ASCII、GBK、万国码等常见字符集及其在编码解码中的应用。
摘要由CSDN通过智能技术生成

一,File类


1,一般用于文件的信息获取,移动和删除操作,包含文件夹


public class FileMethods {

    public static void main(String[] args) {
    
        ///文件信息
//        File f=new File("D:\\chromeDownload\\男孩写作业透明底图.png");
        //项目下的文件
        File f=new File("demo/src/data.txt");
//        File f=new File("D:/");
        //获取绝对路径
        System.out.println(f.getAbsolutePath());
        //定义路径
        System.out.println(f.getPath());
        //获取文件名
        System.out.println(f.getName());
        //获取文件大小
        System.out.println(f.length());
        //获取文件最后修改时间
        Long time=f.lastModified();
        String format = new SimpleDateFormat("yyyy-MM-dd").format(time);
        System.out.println(format);
        //判断是否为文件
        System.out.println(f.isFile());
        //判断是否为文件夹
        System.out.println(f.isDirectory());


        ///删除文件
        try {
            File f2=new File("demo/src/data1.txt");
            System.out.println(f2.createNewFile());//不需要
            f2.mkdir();//一级目录创建
            f2.mkdirs();//多级目录创建
            f2.delete();//删除文件,空文件夹,占用文件
        }catch (Exception e){

        }

	//删除文件
	   private void removeFile(String filePath) {
	       if (StringUtils.isEmpty(filePath)) {
	           return;
	       }
	       File file = new File(filePath);
	       if (file.exists()) {
	           file.delete();
	       }
	   }

        ///文件遍历
        File f3=new File("demo");
        String[] list = f3.list();//list和 返回类型不同
        File[] files = f3.listFiles();//调用者不存在,文件,返回null,空文件夹,0,
        for(String name:list){
            System.out.println(name); //获取一级文件目录
        }
    }
}

项目指定位置路径,文件相对路径设置


   public static final String TEMP_PATH = System.getProperty("user.dir") + File.separator + "temp";
   

在这里插入图片描述

2,多级文件夹中查询指定文件(递归使用)


//多级文件夹中查询指定文件
public class FileSearch {

    public static void main(String[] args) {
        searchfile(new File("D:\\myfiles"), "learn");
    }

    public static void searchfile(File dir, String filename) {
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file.isFile()) {
                        if (file.getName().contains(filename)) {
                            System.out.println("找到了");
                        }
                    } else {
                        searchfile(file, filename);
                    }
                }
            }
        } else {
            System.out.println("找不到");
        }
    }
}


二,字符集


1,字符集

一种编码规则,可以将任何字符转换为十进制数值表示,十进制再转换为二进制
在这里插入图片描述
注意:英文和数字再任何国家都是只占用一个字节,编码与解码字符集必须一致,否则乱码

ASCII 美国编码,主要用于显示现代英语和其他西欧语言
GBK 中国编码,一个中文占用2个字节,兼容ASCII Unicode
万国码,包括世界所有国家的文字编码,兼容ASCII

2,编码-解码代码:


public class FileDecode {
    public static void main(String[] args) throws Exception {
        String name="woai中国";
        //编码
        byte[] bytes=name.getBytes("GBK");
        System.out.println(bytes.length);
        System.out.println(Arrays.toString(bytes));
        //解码(默认utf-8)
        String r1=new String(bytes);
        System.out.println(r1);
        String rs=new String(bytes,"GBK");
        System.out.println(rs);

    }
}

输出:
在这里插入图片描述


三,IO流


在这里插入图片描述

1,流类型:

字节(音频视频文件)
字符(适用文本文件)
在这里插入图片描述

在这里插入图片描述


四,字节流


1,方法定义

在这里插入图片描述

2,代码

文件内容:
在这里插入图片描述

代码1:

public class FileInputStream01 {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("D:\\projectSaas\\ws-demo\\src\\data.txt");

        int b1=fileInputStream.read();
        System.out.println((char) b1);

        int b2=fileInputStream.read();
        System.out.println((char) b2);

    }
}

输出:
在这里插入图片描述


代码2:

public class FileInputStream01 {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("D:\\projectSaas\\ws-demo\\src\\data.txt");

//        int b1=fileInputStream.read();
//        System.out.println((char) b1);
//
//        int b2=fileInputStream.read();
//        System.out.println((char) b2);

        int b;
        while ((b=fileInputStream.read())!=-1){
            System.out.println((char) b);
        }

    }
}

输出:
在这里插入图片描述
文件内容:
在这里插入图片描述


代码3:

public class FileInputStream01 {
    public static void main(String[] args) throws Exception {
        FileInputStream is = new FileInputStream("D:\\projectSaas\\ws-demo\\src\\data.txt");
        byte[] buffer=new byte[3];
        int b;
        while ((b=is.read(buffer))!=-1){
            String rs=new String(buffer);
            System.out.println(rs);
        }
    }
}

输出:
在这里插入图片描述


在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

四,文件拷贝

在这里插入图片描述

1,代码

public class FileInputStream01 {
    public static void main(String[] args) throws Exception {
        FileInputStream is = null;
        FileOutputStream os = null;
        //int a=1/0
        try {
            is = new FileInputStream("D:\\projectSaas\\ws-demo\\src\\data.txt");
            os = new FileOutputStream("D:\\projectSaas\\ws-demo\\src\\data02.txt");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            System.out.println("复制完了!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

五, 资源释放

1,基础做法

在这里插入图片描述
代码:


public class FileInputStream01 {
    public static void main(String[] args) throws Exception {
        FileInputStream is = null;
        FileOutputStream os = null;
        //int a=1/0
        try {
            is = new FileInputStream("D:\\projectSaas\\ws-demo\\src\\data.txt");
            os = new FileOutputStream("D:\\projectSaas\\ws-demo\\src\\data02.txt");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            System.out.println("复制完了!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2,改进(推荐):

在finally模块中释放资源,代码过于冗余,所以可以使用jdk7来释放IO流
在这里插入图片描述

代码:


public class FileInputStream01 {
    public static void main(String[] args) throws Exception {
        try (
                FileInputStream is = new FileInputStream("D:\\projectSaas\\ws-demo\\src\\data.txt");
                FileOutputStream os = new FileOutputStream("D:\\projectSaas\\ws-demo\\src\\data02.txt");
                MyConnect connect=new MyConnect();
        ) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            System.out.println("复制完了!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class MyConnect implements AutoCloseable{
    @Override
    public void close() throws IOException{
        System.out.println("资源释放");
    }
}

注意:这里有2个坑点

1,FileInputStream 其实已经实现了AutoCloseable接口,所以无需再次自己写一个实现接口,

但是这里需要注意的是,对于没有实现了AutoCloseable接口的类,还是需要自己写实现类并调用,

所以安全起见,还是写上为好,特殊情况另论。

 MyConnect connect=new MyConnect();   //实现AutoCloseable接口的类可略此行代码

2,不要嵌套写

错误写法:

这样会导致FileInputStream流无法自动关闭,

从而导致在调用 file.delete() 方法的时候,删除文件失败,因为流未关闭,

导致文件处于占用状态,文件从而删除失败

try (OutputStream outputStream = response.getOutputStream();
     //加载pdf附件到PDF流中
     PDDocument document = PDDocument.load(new FileInputStream(file));
     MyConnect connect = new MyConnect();
	) 

正确写法:

try (OutputStream outputStream = response.getOutputStream();
     FileInputStream fileInputStream = new FileInputStream(file);
     //加载pdf附件到PDF流中
     PDDocument document = PDDocument.load(fileInputStream);
     MyConnect connect = new MyConnect();
	) 

六,字符流读取

1,示意图

在这里插入图片描述

2,代码


public class FileInputStream03 {
    public static void main(String[] args) throws Exception {
        Reader fr=new FileReader("D:\\projectSaas\\ws-demo\\src\\data.txt");
        char[] buffer=new char[1024];
        int len;
        while ((len=fr.read(buffer))!=-1){
            String rs=new String(buffer,0,len);
            System.out.println(rs);
        }
    }
}

public class FileInputStream04 {
    public static void main(String[] args) throws Exception {
        Writer fw=new FileWriter("ws-demo\\src\\data.txt",true);
        fw.write("123");
        fw.write(97);
        fw.write("我");
        fw.write("\r\n");

        fw.write("中国");
        fw.write(100);
        fw.write("她");
        fw.flush();
        fw.write("-----");
        fw.write("我爱你,中国",0,5);
        fw.close();
//        fw.write("+++++");

    }
}

输出:
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值