IO流复制图片
package IODemo;/*** @author Alina* @date 2021年11月14日 4:32 下午* 復制文件到指定目錄**/
import java.io.*;
public class IOcopyfile {public static void main(String[] args) {CopyDir(new File(“源文件”),new File(“目標文件”));}public static void CopyDir(File source,File target){//獲取數據源下所有目錄名字String SourceDirName = source.getName();//System.out.print(SourceDirName);//在新目錄下創建同樣的文檔,只有File 類有創建文件的功能File TargetNewDir = new File(target,SourceDirName);// System.out.print(TargetNewDir);//創建新目錄TargetNewDir.mkdir();//2.遍歷數據源下所有文件File[] files = source.listFiles();//使用for循環遍歷目錄下所有文件for(File sourceFile: files){// System.out.print(sourceFile);// 定義字符串,存儲文件的名字String sourceFileName = sourceFile.getName();//在新目錄下創建相同的文件名File newTargetFileName = new File(TargetNewDir,sourceFileName);//復制文件copyFunction(sourceFile,newTargetFileName);}}public static void copyFunction(File source,File target){FileInputStream fis = null;FileOutputStream fos = null;try{fis = new FileInputStream(source);fos = new FileOutputStream(target);byte[] bytes = new byte[1024];int s = 0;while ((s = fis.read(bytes))!=-1){fos.write(bytes,0,s);}}catch (Exception e){throw new RuntimeException("復制失敗");}finally {try{if (fos != null){fos.close();}}catch (Exception e){throw new RuntimeException("運行失敗");}finally {try {if (fis!=null) {fis.close();}}catch (Exception e){throw new RuntimeException("運行失敗");}}}}
}
總結
- 上一篇: java字符串排序_对字符串排序持一种宽
- 下一篇: arcpy使用