Java는 파일을 처리 할 수있는 IO 작동 클래스를 제공하지만. 그러나 파일을 복사 할 방법이 없습니다. 프로그램 복사는 프로그램 관련 많은 파일을 처리해야 할 때 중요한 작업입니다. 그러나 Java 파일을 복사하는 몇 가지 방법이 있으며 다음은 가장 인기있는 방법입니다.
1. FILESTREAMS를 사용하여 복사하십시오
이것은 한 파일의 내용을 다른 파일에 복사하는 가장 전형적인 방법입니다. FileInputStream을 사용하여 파일 A의 바이트를 읽고 FileOutputStream을 사용하여 파일 B에 씁니다. 이것이 첫 번째 방법의 코드입니다.
개인 정적 void CopyFileUsingFilestreams (파일 소스, 파일 DEST) IOException {inputStream input = null; 출력 스트림 출력 = NULL; try {input = new FileInputStream (소스); output = 새 FileOutputStream (dest); 바이트 [] buf = 새로운 바이트 [1024]; int bytesread; while ((bytesread = input.read (buf))> 0) {output.write (buf, 0, bytesread); }} 마침내 {input.close (); output.close (); }} 보시다시피 우리는 데이터를 시도하기 위해 여러 읽기 및 쓰기 작업을 수행하므로 비효율적 인 방법이어야하며 다음 방법은 새로운 방법을 볼 수 있습니다.
2. filechannel을 사용하여 복사하십시오
Java Nio에는 전송 프롬 메소드가 포함되어 있으며 문서를 기반으로 파일 스트림보다 빠르게 복사해야합니다. 두 번째 방법에 대한 코드는 다음과 같습니다.
개인 정적 void CopyFileUsingFileChannels (파일 소스, 파일 DEST) IOException {FilEchannel InputChannel = null; filechannel outputChannel = null; {inputChannel = new FileInputStream (source) .getChannel (); outputChannel = 새 FileOutputStream (dest) .getChannel (); outputChannel.Transferfrom (입력 채널, 0, inputChannel.size ()); } 마침내 {inputChannel.close (); outputchannel.close (); }}3. Commons IO를 사용하여 복사하십시오
Apache Commons IO는 파일 클래스에 복사 파일 메소드를 제공하며 한 파일을 다른 파일에 복사하는 데 사용할 수 있습니다. 이미 프로젝트를 사용하고있을 때 Apache Commons FileUtils 클래스를 사용할 때 매우 편리합니다. 기본적 으로이 클래스는 Java Nio Filechannel Internals를 사용합니다. 이것은 세 번째 방법의 코드입니다.
개인 정적 void CopyFileUsingApacheCommonsio (파일 소스, 파일 DEST)는 ioException {fileUtils.copyFile (소스, dest); }4. Java7의 파일 클래스를 사용하여 복사하십시오
Java 7에 대한 경험이있는 경우 복사 방법을 사용하여 한 파일에서 다른 파일로 복사 할 수 있습니다. 이것은 네 번째 방법에 대한 코드입니다.
개인 정적 void CopyFileUsingJava7files (파일 소스, 파일 DEST) IOException {files.copy (source.topath (), dest.topath ()); }Java 파일을 다른 디렉토리에 복사하기위한 구현 코드를 살펴 보겠습니다. 특정 코드는 다음과 같습니다.
package com.util; import java.io.file; import java.io.fileInputStream; import java.io.fileoutputStream; import java.io.inputStream; public class testhtml {/** * 복사 * @param oldpath 원본 파일 경로 : c : /fqf.txt * @param newpath path is : f : /fqf. @return boolean */ public void CopyFile (String OldPath, String NewPath) {try {int bytesum = 0; int byteread = 0; 파일 OldFile = 새 파일 (OldPath); if (OldFile.exists ()) {// inputStream instream = new FileInputStream (OldPath); // 원본 파일에서 읽습니다. fileoutputStream fs = new FileOutputStream (newPath); 바이트 [] 버퍼 = 새로운 바이트 [1444]; int 길이; while ((byteread = instream.read (buffer))! = -1) {bytesum += byteread; // 파일 크기 System.out.println (바이트); fs.Write (버퍼, 0, Byteread); } instream.close (); }} catch (예외 e) {System.out.println ( "단일 파일 복사 오류"); e.printstacktrace ();}}/** * 복사 후 C :/fqf * @param newpath 문자열 경로는 다음과 같은 전체 폴더 컨텐츠를 복사 * @param oldpath 문자열 원본 파일 경로 : f :/fqf/ff * @return boolean */public void void void older (string oldpath, string newpath) {(new Pipe (newpath) (newpath). // 폴더가 존재하지 않으면 새 폴더 파일을 만듭니다. a = 새 파일 (OldPath); 문자열 [] file = a.list (); 파일 온도 = null; for (int i = 0; i <file.length; i ++) {if (OldPath.endswith (file.separator)) {temp = new File (OldPath+file [i]); } else {temp = 새 파일 (OldPath+file.separator+file [i]); } if (temp.isfile ()) {fileInputStream input = new FileInputStream (temp); fileoutputStream output = new FileOutputStream (newPath + "/" + (temp.getName ()). toString ()); 바이트 [] B = 새로운 바이트 [1024 * 5]; int len; while ((len = input.read (b))! = -1) {output.write (b, 0, len); } output.flush (); output.close (); input.close (); } if (temp.isdirectory ()) {// subfolder copyfolder (OldPath+"/"+file [i], newPath+"/"+file [i]); }}} catch (예외 e) {System.out.println ( "전체 폴더 컨텐츠 작업을 복사 오류"); e.printstacktrace ();}} public static void main (string [] args)은 예외를 던지고 {// // 이것은 소스 파일입니다. afterfile = 새 파일 ( "c : /users/administrator/desktop/jiekou0/untitled-2.html"); /// // 이전 파일을 읽기 위해 파일 입력 스트림을 정의합니다. // fileInputStream fis = 새 FileInputStream (prefore file); newfile file file에 쓰기로 작성하여 파일 출력 스트림을 정의합니다. fileoutputStream (후 파일); /// // 파일 캐시 영역 // byte [] b = new Byte [1024]; // // 파일 캐시 영역에서 파일 스트림 정보를 읽습니다. 읽기 결과가 -1이 아닌 경우 파일이 읽지 않았으며 읽지 않았 음을 의미합니다 .// while (fis.read (b)! = -1) {// // 캐시 영역에서 내용을 후방 파일에 작성 // fos.write (b); // fos.flush (); //} string. OldPath = "c : /users/administrator/desktop/untitled-2.html"; String newPath = "c : /users/administrator/desktop/jiekou0/untitled-2.html"; testhtml t = new testhtml (); t.copyfile (newpath,});요약
위의 것은 Java에서 파일을 복사하는 4 가지 방법과 편집기가 소개 한 다른 디렉토리에 파일을 복사하는 예제 코드입니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!