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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步