자바

자바 파일복사, 파일삭제, 파일이동 예제및 설명 [김철수홍길동]

세상 모든 것 들은 그 자신을 위해 존재한다. 2021. 3. 22. 21:54

파일 복사, 삭제, 이동을 처리하는 클래스를 만들어서 

필요시에 생성자를 만들어 사용하면 편리합니다.

 

아래에 나오는 예제를 복붙하여 사용하시면 되겠습니다.

설명은 주석부분에 있습니다.

 

먼저 Main파일입니다.

예제 설명을 위해서 만들었습니다.

TestMain.java 

import java.time.DayOfWeek;
import java.time.LocalDate;

public class TestMain {

	public static void main(String[] args) {
		
		//원본파일의 경로를 지정합니다.
		String originalFilePath = "c:/temp/test/a.jpg";
		
		//사본파일이 저장될 위치를 지정합니다.
		String copyDirPath = "c:/temp/test/copy_dir";
		
		//사본파일이 저장될 위치와 파일명을 지정합니다.
		String copyFilePath = copyDirPath+"/"+"a_copy.jpg";
		
		//복사,삭제,이동을 처리하는 클래스의 생성자를 만들어 줌니다.
		CopyOrDel cnd = new CopyOrDel(originalFilePath,copyFilePath,copyDirPath);
		
		//파일을 복사하는 메소드를 실행시킵니다.
		//정상처리 되었을때는 1을 실패시는 -1를 리턴하게 됩니다.
		int nCopyReturn = cnd.copy();
		
		//원본파일을 삭제 하는 메소드를 생행시킵니다.
		//정상처리 되었을때는 1을 실패시는 -1를 리턴하게 됩니다.
		int nDelReturn = cnd.del();
/*------복사후 원본을 삭제하면 파일이동이 됩니다.
		그래서 위의 경우는 파일명이 변경되면서 이동이 된경우 입니다.
		복사만 할경우에는 위의 cnd.copy(); 만 실행 하시면 됩니다.
		물론 삭제시에는 아래부분의 cnd.del();을 실행하면  되겠습니다.
*/		
		
		//처리결과를 알아보기 위한 부분입니다.
		//두변수모두가 1 이면 파일복사,파일삭제가 된경우라 결국 파일이동이 정상적으로 
		//되었다는 메세지입니다.
		if (nCopyReturn == 1 && nDelReturn ==1) {
			System.out.println("파일이동성공");
		}
		
		//파일복사가 성공했다는 메세지 출력입니다.
		else if (nCopyReturn == 1) {
			System.out.println("파일복사성공");
		}
		
		//파일삭제가 성공했다는 메세지 출력입니다.
		else if (nDelReturn == 1) {
			System.out.println("파일삭제성공");
		}
		
		//실패시에는 CopyOrDel클래스에서 에러메세지를 출력합니다.
		
		
	}
}



 

두 번째는 실제로 처리가 이루어지는 클래스입니다.

 

그대로 복붙 하셔서 사용하시면 되겠습니다.

CopyOrDel.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class CopyOrDel {
	
	public String originalFilePath;
	public String copyFilePath;
	public String copyDirPath;

	//생성자를 만들때 원본파일, 사본파일,사본파일저장위치의 경로정보를 받는다.
		public CopyOrDel(String originalFilePath, String copyFilePath,String copyDirPath) {
		this.originalFilePath = originalFilePath;
		this.copyFilePath = copyFilePath;
		this.copyDirPath = copyDirPath;
	}

//--------------------------copy()----------------------------------------------------		
	//복사성공시 1을 돌려주고 실패시 -1를 돌려준다.
	//복사하는 메소드	
	public int copy() {
		File originalFile = new File(originalFilePath);
		File copyFile = new File(copyFilePath);
		File dirCopyFile = new File(copyDirPath);
		
		//복사될 장소의 디렉토리가 존재하지 않으면 만들어준다.
		if(!dirCopyFile.exists()) {
			dirCopyFile.mkdirs();
		}
		
		try {
			//파일의 내용을 읽어오기위한 준비
			FileInputStream fis = new FileInputStream(originalFile);
			
			//파일의 내용을 쓰기 위한 준비
			FileOutputStream fos = new FileOutputStream(copyFile);

			//파일을 읽고 쓰기를 합니다. 
			int nRealByte = 0;
			while ((nRealByte = fis.read()) != -1) {
				fos.write(nRealByte);
			}
			
			//파일스트림을 닫아줍니다.
			fis.close();
			fos.close();

		} catch (Exception e) {
			//파일 처리 실패시 -1를 리턴합니다.
			System.out.println(e.getLocalizedMessage());
			return -1;
		}
		//성공시에 메세지 출력후 1을 리턴합니다.
		System.out.println("copy succeed !!");
		return 1;
	}

//--------------------------del()----------------------------------------------------	
	//삭제하는 메소드
	public int del() {
		File file = new File(originalFilePath);
		
		//파일이 있는지 확인합니다.
		if (file.exists()) {
			
			//혹시난 디렉토리 인지도 확인합니다. 이면 그아래의 파일도 삭제합니다.
			if (file.isDirectory()) {
				File[] filelist = file.listFiles();
				for (int i = 0; i < filelist.length; i++) {
					if (filelist[i].delete()) {
						System.out.println(filelist[i].getName() + "Dirlist- delete succeed !!");
					} else {
						System.out.println(filelist[i].getName() + "Dirlist- delete error");
					}
				}
			}
			if (file.delete()) {
				System.out.println("delete succeed !!");
			} else {
				//파일 삭제가 실패하면 에러메세지출력후 -1를 리턴합니다.
				System.out.println("delete error");
				return -1;
			}
			//파일이 존재하지 않으면 에러메세지를 보내고 -2를 리턴합니다.
		} else {
			System.out.println("not exist !!!");
			return -2;
		}
		//정상처리되면 1를 리턴합니다.
		return 1;
	}
}

 

위의 예제를 실행하면 나오는 Console출력 결과입니다.

copy succeed !!
delete succeed !!
파일이동성공

 

실행 전 탐색기 화면

실행 후 탐색기 화면입니다.

파일명이 변경되면서 위치가 이동된 것을 알 수 있습니다.

복사 후 삭제했으므로 파일 이동의 결과가 나왔습니다.

물론 다른 포맷 파일도 적용이 가능합니다.

 

코딩이 풀리지 않을때는  스트레스도 풀겸 잠시 휴식을 하는것이 ...

 

끝.

 

 

728x90
반응형