【Java、File 文件相关操作】

平常写java时,经常会遇到文件相关的操作。文件读写,基本可以概括为从具体文件(File),到流(Stream),最后到字节(byte[ ]),或者反过来。

也就是说文件操作一切都归结为操作字节:

  • 读 = 将文件通过流读出字节
  • 写 = 将字节通过流写入到文件中

 

 

File相关概念

文件流相关概念

 

File 与 byte[ ] 的转换 

1、把 File 转换为 byte[ ]

  /**
     * 
     * @param file 目标文件
     * @return bytes file的字节数组
     * @throws IOException
     */
private static byte[] getBytesFromFile(File file) throws IOException {
        byte[] bytes = null;
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int len = fis.read(buffer);
        while (len!= -1) {
            baos.write(buffer, 0, len);
            len = fis.read(buffer);
        }

        bytes = baos.toByteArray();

        if(ArrayUtils.isEmpty(bytes)){
            System.out.println("byte[]为空");
        }else {
            System.out.println("byte[]不为空");
        }

        return bytes;
    }

2、byte[ ] 转换为 File

File file = new File("E:/xxx/xxx/alan.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes,0,bytes.length);

 

文件复制

private static void copyFile(File fileSource,File fileTarget) throws IOException {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = new FileOutputStream(fileTarget);
        try{
            fis = new FileInputStream(fileSource);
            bis = new BufferedInputStream(fis);
            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while(i!=-1){
                fos.write(buffer,0,i);
                i=bis.read(buffer);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            bis.close();
            fis.close();
            fos.close();
        }
    }

 

对象与文件

1、把对象写入文件中


        File fileTarget = new File("E:/xxx/xxx");

        User user = new User();

        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(fileTarget));) {
            oos.writeObject(user);
        } catch (Exception e) {
            System.out.println("写入异常", e);
        }

2、把文件内容读进对象里

        File file = new File("E:/xxx/xxx");

        User user = null;

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            user = (User) ois.readObject();
        } catch (Exception e) {
            System.out.println("写出异常");
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值