复制文件

public class IOTest {
    public static void main(String[] args) {
        File file = new File("D:\\IoTest");
        if(!file.exists()){ //如果不存在则创建文件夹
            file.mkdir();//创建文件夹
        }else{
            file.delete();//先删除 在创建
            file.mkdir();
        }
        try{
           /* BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter("D:\\IoTest\\hzm.test"));
            bufferedWriter.write("heoll.word");
            bufferedWriter.close();*/
           //采用复制文件
            copyFile("D:\\img\\1.png","D:\\IoTest\\1.png");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //复制文件

    /**
     *
     * @param source 源文件
     * @param dest 新文件
     * @throws IOException
     */
   public static void copyFile(String sourcePath, String destPath) throws IOException{
       File source = new File(sourcePath);
       File dest = new File(destPath);
       InputStream inputStream = null;
       OutputStream outputStream = null;
       try{
           inputStream =new FileInputStream(source);
           outputStream =new FileOutputStream(dest);
           byte [] bytes =new byte[1024];
           int bytesRead;
           while ((bytesRead = inputStream.read(bytes))>0){
               outputStream.write(bytes,0,bytesRead);
           }
       }catch (Exception e){
           e.printStackTrace();
       }finally {
          if(inputStream !=null){
              inputStream.close();
          }
           if(outputStream !=null){
               outputStream.close();
           }
       }
   }

}

 

posted @ 2019-04-02 10:25  卖单词谋生  阅读(142)  评论(0编辑  收藏  举报