📂java
🔖javaio
2020-11-16 18:05阅读: 74评论: 0推荐: 0

java常用IO

1.java递归删除某一文件夹下的文件

复制代码
 1 /**
 2      * 递归删除文件
 3      * @param file
 4      */
 5     public static void delAll(File file) {
 6         //获取包含file对象对应的子目录或者文件
 7         File[] b = file.listFiles();
 8         for (int i = 0; i < b.length; i++) {
 9             //判断是否为文件
10             if (b[i].isFile()) {
11                 //如果是就删除
12                 b[i].delete();
13             } else {
14                 //否则重新递归到方法中
15                 delAll(b[i]);
16             }
17         }
18         //最后删除该目录中所有文件后就删除该目录
19         file.delete();
20     }
21 
22     public static void main(String[] args) {
23         delAll(new File("D:\\test"));
24     }
复制代码

2.java拷贝

复制代码
 1 public static void main(String[] args) throws IOException {
 2 
 3         BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("D:\\a.avi"));
 4         BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream("E:\\b.avi"));
 5         byte[] bytes = new byte[1024];
 6         int read=-1;
 7         while ((read=bufferedInputStream.read(bytes))!=-1){
 8             bufferedOutputStream.write(bytes);
 9         }
10         bufferedOutputStream.close();
11         bufferedInputStream.close();
12     }
复制代码

3.java判断路径是否存在不存在就创建

复制代码
 1 public class FileUtil {
 2 
 3     public static void filePathIsExist(String fileURL) {
 4         
 5         File file = new File(fileURL);
 6         //如果文件夹不存在则创建
 7         if (!file.exists() && !file.isDirectory()) {
 8             file.mkdir();
 9         }
10         
11     }
12     
13 }
复制代码

4.判断某路径下文件是否存在,存在就读取出来

复制代码
 1 File file = new File("FILE_PATH");
 2             if (file.exists()){
 3                 //取得文件的字节输入流
 4                 FileInputStream fileInputStream = new FileInputStream(file);
 5                 //创建文件长度的buf fileInputStream.available()返回文件长度,使用available()获得文件长度,结合数组获取就不用再进行长度判断,可以直接创建对应大小的字符数组直接输出
 6                 byte[] buf=new byte[fileInputStream.available()];
 7                 //读取到buf中  
 8                 fileInputStream.read(buf);
 9                 fileInputStream.close();
10                 String respStr=new String(buf);
11             }
复制代码

 

  

本文作者:zydjjcpdszylddpll

本文链接:https://www.cnblogs.com/jyfs/p/13986363.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   zydjjcpdszylddpll  阅读(74)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起