Java를 사용하여 파일 복사는 어디에서나 사용할 수 있습니다. 다음은 참조 수업입니다. 총 두 가지 방법이 있습니다.
public static boolean copyfile (문자열 srcfilename, String destfilename, 부울 오버레이); public static boolean copydirctory (문자열 srcdirname, String destdirname, 부울 오버레이);
안에:
srcfilename 파일 이름을 복사합니다
descfilename 대상 파일 이름
오버레이 대상 파일이 존재하는 경우 오버레이를 덮어 쓸지 여부. 사본이 성공하면 true를 반환하고 그렇지 않으면 false를 반환합니다.
암호:
import java.io.file; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputstream; import java.io.outputStream; import javax.swing.joptionpane; / ** * 파일 또는 폴더 복사 * * zww */ public class copyfileutil {private static string message = ""; / ** * 단일 파일 복사 * * @param srcfilename * 복사 할 파일 이름 * @param descfilename * target 파일 이름 * @param 오버레이 * 대상 파일이 존재하는 경우, 복사를 성공적으로 작성하는지 여부 * @return true, 그렇지 않으면 false */ public static boolean couplfile (string srcfilename, strestff) = 새 파일 (srcfilename); // 소스 파일이 존재하는지 (! srcfile.exists ()) {message = "소스 파일 :" + srcfilename + "존재하지 않는다!"; joptionpane.showmessagedialog (null, message); 거짓을 반환합니다. } else if (! srcfile.isfile ()) {message = "복사 파일 실패, 소스 파일 :" + srcfilename + "파일이 아님!"; joptionpane.showmessagedialog (null, message); 거짓을 반환합니다. } // 대상 파일이 파일에 존재하는지 여부를 결정합니다. destFile = 새 파일 (destFilename); if (destfile.exists ()) {// 대상 파일이 존재하고 (오버레이)를 덮어 쓰기를 허용하는 경우 {// 대상 파일이 디렉토리인지 또는 단일 파일 새 파일 (destFileName) .delete ()에 관계없이 기존 대상 파일을 삭제합니다. }} else {// 대상 파일이 존재하지 않는 디렉토리가있는 경우 (! destFile.getParentFile (). Exists ()) {// 대상 파일이 존재하지 않는 디렉토리 (! destFile.getParentFile ()) {// 파일을 복사하지 못했습니다. 대상 파일을 작성하는 데 실패했습니다. }}} // 파일을 복사 int byteread = 0; // inputStream in = null을 읽는 바이트 수; outputStream out = null; try {in = new FileInputStream (srcfile); out = new FileOutputStream (destFile); 바이트 [] 버퍼 = 새로운 바이트 [1024]; while ((byteread = in.read (buffer))! = -1) {out.write (buffer, 0, byteread); } true를 반환합니다. } catch (filenotfoundException e) {return false; } catch (ioexception e) {return false; } 마침내 {try {if (out! = null) out.close (); if (in! = null) in.close (); } catch (ioexception e) {e.printstacktrace (); }}}}} / ** * 전체 디렉토리의 내용을 복사 * @param srcdirname * 복사 할 디렉토리의 디렉토리 이름 * @param destdirname * 대상 디렉토리 이름 * @param 오버레이 * 대상 디렉토리가 존재하는 경우 사본이 성공 여부에 관계없이, 그렇지 않으면, 그렇지 않으면, false * / public stat rist (strat) destdirname, 부울 오버레이) {// 소스 디렉토리가 파일 SRCDIR = 새 파일 (srcdirname)에 있는지 결정합니다. if (! srcdir.exists ()) {message = "복사 디렉토리 실패 : 소스 디렉토리" + srcdirname + "do n't indiversity!"; joptionpane.showmessagedialog (null, message); 거짓을 반환합니다. } else if (! srcdir.isdirectory ()) {message = "복사 디렉토리 실패 :" + srcdirname + "디렉토리가 아님!"; joptionpane.showmessagedialog (null, message); 거짓을 반환합니다. } // 대상 디렉토리 이름이 파일 Delimiter로 끝나지 않으면 파일 Delimiter를 추가하십시오 if (! destDirName.endSwith (file.Separator)) {destDirName = destDirName + file.separator; } file destdir = 새 파일 (destdirname); // 대상 폴더가 존재하는 경우 (destdir.exists ()) {// 오버레이가 허용되면 기존 대상 디렉토리를 삭제합니다. if (Orday) {새 파일 (destdirname) .delete (); } else {message = "복사 디렉토리 실패 : 대상 디렉토리" + destdirname + "이미 존재했습니다!"; joptionpane.showmessagedialog (null, message); 거짓을 반환합니다. }} else {// 대상 디렉토리 시스템을 만듭니다. if (! destdir.mkdir ()) {System.out.println ( "복사 디렉토리 실패 : 대상 디렉토리 생성 실패!"); 거짓을 반환합니다. }} 부울 플래그 = true; file [] files = srcdir.listfiles (); for (int i = 0; i <files.length; i ++) {// 파일 복사 if (files [i] .isfile ()) {깃발 = CopyFileUtil.copyFile (files [i] .getAbsolutePath (), destDirname+파일 [i] .getName (), Orday); if (! 플래그) 파손; } else if (files [i] .isdirectory ()) {flag = copyfileutil.copydirectory (files [i] .getabsolutepath (), destdirname + 파일 [i] .getName (), 오버레이); if (! 플래그) 파손; }} if (! flag) {message = "복사 디렉토리" + srcdirname + "to" + destdirname + "실패!"; joptionpane.showmessagedialog (null, message); 거짓을 반환합니다. } else {return true; }} public static void main (String [] args) {String srcdirname = "c :/test/test0/test1"; String destdirname = "c :/ttt"; Copyfileutil.copydirctory (srcdirname, destdirname, true); }}멀티 스레드 최적화를 고려하지 않고 단일 스레드 파일을 복사하는 가장 빠른 방법은 (파일이 클수록 더 많은 이점이 많을수록 일반적으로 사용되는 방법보다 30+% 더 빠릅니다) :
개인 정적 무효 Niotransfercopy (파일 소스, 파일 대상) {filechannel in = null; filechannel out = null; fileInputStream instream = null; FileOutputStream Outstream = NULL; try {instream = new FileInputStream (소스); Outstream = 새 FileOutputStream (대상); in = instream.getChannel (); out = outstream.getChannel (); in.transferto (0, in.size (), Out); } catch (ioexception e) {e.printstacktrace (); } 마침내 {Close (instream); 닫기 (in); 닫기 (아웃 스트림); 닫기 (out); }}복제 진행 상황을 모니터링 해야하는 경우 두 번째로 빠른 방법을 사용할 수 있습니다 (버퍼의 크기에주의를 기울이면 속도에 큰 영향을 미칩니다).
개인 정적 무효 Niobuffercopy (파일 소스, 파일 대상) {filechannel in = null; filechannel out = null; fileInputStream instream = null; FileOutputStream Outstream = NULL; try {instream = new FileInputStream (소스); Outstream = 새 FileOutputStream (대상); in = instream.getChannel (); out = outstream.getChannel (); 바이트 버퍼 버퍼 = Bytebuffer.allocate (4096); while (in.read (buffer)! = -1) {buffer.flip (); out.write (버퍼); buffer.clear (); }} catch (ioexception e) {e.printstacktrace (); } 마침내 {Close (instream); 닫기 (in); 닫기 (아웃 스트림); 닫기 (out); }}일반적으로 사용되는 방법 1은 다음과 같습니다.
개인 정적 void CustomBufferBufferedStreamCopy (파일 소스, 파일 대상) {inputStream fis = null; outputStream fos = null; try {fis = new bufferedInputStream (new FileInputStream (source)); fos = new bufferedOutputStream (new FileOutputStream (target)); 바이트 [] buf = 새로운 바이트 [4096]; int i; while ((i = fis.read (buf))! = -1) {fos.write (buf, 0, i); }} catch (예외 e) {e.printstacktrace (); } 마침내 {Close (fis); 닫기 (fos); }}일반적으로 사용되는 방법 2는 다음과 같습니다.
개인 정적 void CustomBufferstreamCopy (파일 소스, 파일 대상) {inputStream fis = null; outputStream fos = null; try {fis = new FileInputStream (source); fos = 새 파일 아웃 putStream (target); 바이트 [] buf = 새로운 바이트 [4096]; int i; while ((i = fis.read (buf))! = -1) {fos.write (buf, 0, i); }} catch (예외 e) {e.printstacktrace (); } 마침내 {Close (fis); 닫기 (fos); }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.