Io基本操作

来源:互联网 发布:knn算法例题 编辑:程序博客网 时间:2024/05/17 03:12

 

/**
  * 新建文件

  * @param path 文件路径
  */
 public static void createFile(String path) {
  File file = new File(path);
  File parentFile = new File(file.getParent());
  if (file.exists()) {
   System.out.println("文件已经存在");
  } else {
   if (!parentFile.exists()) {
    System.out.println("父目录不存在准备创建");
    file.getParentFile().mkdirs();
    try {
     file.createNewFile();
     if (file.exists()) {
      System.out.println("创建成功");
     } else {
      System.out.println("创建失败");
     }
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 

 

/**
  * 删除文件
  * @param path 文件路径
  */
 public static void deleteFile(String path){
  File file = new File(path);
  if(file.exists()){
   file.delete();
   System.out.println("删除成功");
  }else{
   System.out.println("文件不存在");
  }
 }

 

/**
  * 复制文件
  *
  * @param fromPath
  * @param toPath
  */
 public static void copyFileWithBuffer(String fromPath, String toPath) {
  BufferedInputStream bis = null;
  BufferedOutputStream bos = null;

  try {
   bis = new BufferedInputStream(new FileInputStream(fromPath));
   bos = new BufferedOutputStream(new FileOutputStream(toPath));
   byte[] buf = new byte[1444];
   int readLine = 0;
   while ((readLine = bis.read(buf)) != -1) {
    bos.write(buf, 0, readLine);
    bos.flush();
   }

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (null != bis || null != bos) {
     bis.close();
     bos.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

 

基本操作就这些了 当然很多时候的需求是要移动某些文件很简单 copy 然后delete 就可以了

这样简单的io操作只适用于少量文件的操作。像从服务器或ftp 下载大量文件并针对这些文件做操作的时候可能要复杂点 前些日子做了一个类似的有时间再整理出来

 

原创粉丝点击