Java IO流 字符流 字节流 缓冲流 文件复制 编码问题 xlsx类型文件生成 创建临时文件

本文介绍了Java中的IO操作,包括计算文件大小的递归方法,删除文件的实现,使用FileInputStream和FileOutputStream进行读写,以及如何复制文件和文件夹。还讨论了字节流和字符流的区别,缓冲流提高效率的作用,以及处理编码问题。最后提到了如何创建和处理xlsx类型的文件。
摘要由CSDN通过智能技术生成

Java IO流

文件

1、获取文件大小,涉及知识点(File,递归)

递归:自己调自己

public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Desktop\\test");
        System.out.println(fileSize(file));
    }
    //获取当前文件夹大小
    public static long fileSize(File file){
        long len = 0;
        //判断文件是否存在
        if (file.exists() && file.isDirectory()){
            //获取当前文件夹下的文件数组
            File[] files = file.listFiles();
            for (File file1 : files) {
                //判断当前读取的是否是文件
                if (file1.isFile()){
                    len += file1.length();
                }else {
                    //如果当前文件为文件夹则递归调用
                    long size = fileSize(file1);
                    len += size;
                }
            }
        }
        return len;
    }
}
2、删除文件,涉及知识点(File,递归)

复制文件夹时目标文件夹建在源文件目录下时,可用来删除套娃文件夹

public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Desktop\\test");
        deleteFile(file);
    }

    public static void deleteFile(File file){
        //判断文件是否存在
        if (file.exists() && file.isDirectory()){
            //获取当前文件夹下的文件数组
            File[] files = file.listFiles();
            for (File file1 : files) {
                //判断当前读取的是否是文件
                if (file1.isFile()){
                    file1.delete();
                }else {
                    deleteFile(file1);
                }
            }
        }
        file.delete();
    }

}

字节流

1、读取 FileInputStream

读取当前文件下所有内容

public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Desktop\\test");
        readFile(file);
    }

    public static void readFile(File file) throws IOException {
        //判断文件是否存在
        if (file.exists() && file.isDirectory()){
            //获取当前文件夹下的文件数组
            File[] files = file.listFiles();
            for (File file1 : files) {
                //判断当前读取的是否是文件
                if (file1.isFile()){
                    FileInputStream fileInputStream = new FileInputStream(file1);
                    int read = 0;
                    while((read = fileInputStream.read())>0){
                        System.out.println(read);
                    }
                    //释放资源
                    fileInputStream.close();
                }else {
                    System.out.println("xxxxxxxxxxxxx");
                    //如果当前文件为文件夹则递归调用
                    readFile(file1);
                }
            }
        }
    }

}
2、写入 FileOutputStream
public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Desktop\\test\\11.txt");
        writeFile(file);
    }

    public static void writeFile(File file) throws IOException {
        //判断文件是否存在
        if (file.exists()){
            //判断当前读取的是否是文件
            if (file.isFile()){
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                byte[] by={'H','E','L','L','O'};
                fileOutputStream.write(by);
                //写入指定长度的字节
                fileOutputStream.write(by,2,3);
                fileOutputStream.close();
            }
        }
    }

}

3、复制文件
public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Desktop\\test\\11.txt");
        //a 文件夹要事先建好
        File file1 = new File("C:\\Users\\Desktop\\test\\a");
        copyFile(file,file1);
    }


    //目标文件夹下复制想要复制的文件
    public static void copyFile(File srcDir,File destDir) throws IOException {
        //在目标文件夹下创建同名文件
        File destFile = new File(destDir, srcDir.getName());
        //读取源文件内容并写入目标文件
        FileOutputStream fileOutputStream = new FileOutputStream(destFile);
        //读取源文件内容
        FileInputStream fileInputStream = new FileInputStream(srcDir);

        byte[] bytes = new byte[1024];
        int read ;
        while((read = fileInputStream.read())>0){
            fileOutputStream.write(read);
        }
		//释放资源
        fileInputStream.close();
        fileOutputStream.close();

    }
}

4、复制文件夹

注意目标文件夹不要建在源文件夹中否则将会无限套娃(有判断除外)

public class FileTest {
    public static void main(String[] args) throws IOException {
        //复制文件夹
        File file = new File("C:\\Users\\Desktop\\test");
        File file1 = new File("C:\\Users\\Desktop\\test\\test2");
        copyFolder(file,file1);
    }

    //复制文件夹
    //注意目标文件夹不要建在源文件夹中否则将会无限套娃(有判断除外)
    public static void copyFolder(File srcDir,File destDir) throws IOException{
        if(!(srcDir.exists() && srcDir.isDirectory())){
            throw new RuntimeException("当前文件夹不存在或者不是一个文件夹");
        }
        if(!srcDir.isDirectory()){
            throw new RuntimeException("destDir不是一个文件夹");
        }
        //创建目标文件夹
        File destFolder = new File(destDir, srcDir.getName());
        //创建出目标文件夹,不写的话报错
        destFolder.mkdirs();
        //读取源文件夹下所有文件
        //依次将源文件夹下的内容复制到目标文件下
        File[] files = srcDir.listFiles();
        for (File file : files) {
            //当要复制的是文件时
            if (file.isFile()){
                copyFile(file,destFolder);
            }else{
    				//判断复制的是不是目标文件,禁止套娃
    			if(file.getName().equals(destDir.getName())){
                    //throw new RuntimeException("禁止套娃,当前复制的是目标文件夹");
                    //中止本次循环,接着开始下一次循环,break;return;都会终止掉目前的循环,容易导致文件复制不全
                    continue;
                }
                //当复制的是文件夹时
                copyFolder(file,destFolder);
            }
        }
    }

    //目标文件夹下复制想要复制的文件
    public static void copyFile(File srcDir,File destDir) throws IOException {
        //在目标文件夹下创建同名文件
        File destFile = new File(destDir, srcDir.getName());
        //读取源文件内容并写入目标文件
        FileOutputStream fileOutputStream = new FileOutputStream(destFile);
        //读取源文件内容
        FileInputStream fileInputStream = new FileInputStream(srcDir);

        byte[] bytes = new byte[1024];
        int read ;
        while((read = fileInputStream.read())>0){
            fileOutputStream.write(read);
        }
		//释放资源
        fileInputStream.close();
        fileOutputStream.close();

    }

}

5、编码问题

乱码问题:
1、读取数据时未读完整个字符
以字节流读取为例,UTF-8中汉字占3个字节,字节流每次读取一个字节,则会造成乱码,可以使用字符流来解决。
2、编码格式不一致
例:编码格式为GBK,解码格式为UTF-8,此时会造成乱码,
使用时统一格式可解决

public class FileTest {
    public static void main(String[] args) throws IOException {
        //文件编码 编码相当于加密,把看的懂得文件编码成看不懂的,解码相当于解密,把看不懂的文件解码成看得懂的
        //编码和解码使用的编码格式要一致,不然会乱码
        //UTF-8
        //GBK
        //ANSI 如果安装的时windows的简体中文系统,此时ANSI = GBK ,可以通过查看文件编码验证(可使用工具notepad++)
        File file = new File("C:\\Users\\Desktop\\test\\aa.txt");
        File file1 = new File("C:\\Users\\Desktop\\test\\aa复制.txt");
        code(file);
        code(file1);
    }
    public static void code(File srcDir) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(srcDir);
        byte[] bytes = new byte[1024];
        int read = fileInputStream.read(bytes);
        //charset 设置编码格式
        System.out.println(new String(bytes,"gbk"));
        fileInputStream.close();
    }
}

字符流

一次读取一个字符
FileWriter 写入
FileReader 读取

public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Desktop\\test\\aa.txt");
        File file1 = new File("C:\\Users\\Desktop\\test\\zz.txt");
        copyTxt(file,file1);
    }
    //字符流复制纯文本文件
    public static void copyTxt(File srcDir,File destDir) throws IOException {
        //字符流 写入
        FileWriter fileWriter = new FileWriter(destDir);
        //字符流 读取
        FileReader fileReader = new FileReader(srcDir);
        char[] chars = new char[1];
        int len;
        while ((len= fileReader.read(chars))!=-1){
            fileWriter.write(chars,0,len);
            //刷新缓存,将内存中读取的字符写入文件中(硬盘)
            //fileWriter.flush();
        }
        //释放资源,同时刷新缓存,将内存中读取的字符写入文件中(硬盘)
        fileReader.close();
        //释放资源
        fileWriter.close();

    }
}

缓冲流

减少IO次数,提高读写效率

public class FileTest {
    public static void main(String[] args) throws IOException {
        //字符读取缓冲流
        BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\test\\11.txt"));
        //字符写入缓冲流 true开启续写
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\Desktop\\test\\aa.txt",true));
        buffereder(bufferedReader, bufferedWriter);


        //字节输入缓冲流
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("C:\\Users\\Desktop\\test\\11.txt"));
        //字节输出缓冲流 true开启续写
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("C:\\Users\\Desktop\\test\\aa.txt", true));
        bufferedStream(bufferedInputStream, bufferedOutputStream);
    }

    private static void buffereder(BufferedReader bufferedReader, BufferedWriter bufferedWriter) throws IOException {
        String s;
        while ((s = bufferedReader.readLine()) != null){
            bufferedWriter.write(s);
            // 换行,支持不同系统
            bufferedWriter.newLine();
        }
        //释放资源
        bufferedWriter.close();
        bufferedReader.close();
    }

    private static void bufferedStream(BufferedInputStream bufferedInputStream, BufferedOutputStream bufferedOutputStream) throws IOException {
        byte[] bytes = new byte[10];
        int read;
        while ((read = bufferedInputStream.read(bytes)) != -1){
            //将指定长度的字节写入
            bufferedOutputStream.write(bytes,0,read);
        }
        //释放资源
        bufferedInputStream.close();
        bufferedOutputStream.close();
    }

}

删除原有文件,并重新创建文件

public static File convertByteToFile(byte[] bytes, String filePath) {
        if (bytes == null) {
            return null;
        }
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 每次上传文件之前,需要先将之前的文件删除掉
            File file = new File(filePath);
            // 如果文件夹存在就不创建
            if (!file.exists()) {
                file.mkdirs();
            }
            // 只删除该文件夹下的文件,不删除文件夹
            if (file.isDirectory()) {
                for (File f : file.listFiles()) {
                    f.delete();
                }
            }
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())) + "upload.png";
            File fileUpload = new File(filePath + fileName);
            //父级目录
            File fileParent = fileUpload.getParentFile();
            //判断父级目录是否存在
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            //创建文件
            fileUpload.createNewFile();
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fileUpload));
            bufferedOutputStream.write(bytes);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

xlsx类型文件生成

创建临时文件
File file = File.createTempFile(fileNamePrefix, “.xlsx”);
//删除文件
file.delete();

/**
     * 写入数据逻辑
     *
     * @param oneFileJSONArray   单个文件的数据
     * @param fileNamePrefix     文件名前缀
     * @param processTemplateMap 配置的加工模板
     * @return
     */
    public File createFile(JSONArray oneFileJSONArray, String fileNamePrefix, HashMap<String, String> processTemplateMap) {
        try {
            File file = File.createTempFile(fileNamePrefix, ".xlsx");
            if (oneFileJSONArray.size() == 0) {
                return file;
            }
            OutputStream os = new FileOutputStream(file);
            SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
            sxssfWorkbook.createSheet("sheet1");
            Sheet sheet = sxssfWorkbook.getSheetAt(0);
            //
            for (int i = 0; i < oneFileJSONArray.size(); i++) {
                //一个个实例对象
                JSONObject jsonObject = oneFileJSONArray.getJSONObject(i);
                //配置的响应参数个数
                int responseParamSize = processTemplateMap.size();
                int responseParamChangeSize = processTemplateMap.size();
                //表头行
                Row rowTitle = null;
                if (i == 0) {
                    //只有第一次进来才创建表格title
                    rowTitle = sheet.createRow(0);
                }
                //内容行
                Row row = sheet.createRow(i + 1);
                //解析配置的响应参数
                for (Map.Entry<String, String> entry : processTemplateMap.entrySet()) {
                    if (i == 0) {
                        //创建表格的title内容
                        Cell numTile = rowTitle.createCell((responseParamSize - responseParamChangeSize));
                        numTile.setCellValue(entry.getValue());
                    }
                    //填充表格的数据
                    Object values = jsonObject.get(entry.getKey());
                    Cell cell = row.createCell((responseParamSize - responseParamChangeSize--));
                    cell.setCellValue(excludeNull(values));
                }
            }
            sxssfWorkbook.write(os);
            sxssfWorkbook.close();
            os.close();
            os.flush();
            return file;
        } catch (IOException e) {
            log.error("创建xssfWorkbook出错,文件找不到:", e);
            throw new TradeDatacenterException(TradeDatacenterErrorCode.TARGET_FILE_NOT_EXIST, e.getMessage());
        } catch (Exception e) {
            log.error("创建xssfWorkbook失败:", e);
            throw new TradeDatacenterException(TradeDatacenterErrorCode.TARGET_FILE_NOT_EXIST, e.getMessage());
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值