IT/Java

[Java] java.nio.file.Files 클래스

상짱 2022. 10. 31. 17:40
반응형

- java.nio.file.Files

- since 1.7 

 

- 입출력의 기본이 되는 파일 부분부터 공부를 진행 중이다.

- Files 클래스에 파일 관련 많은 기능들이 제공이 되어서 기본 샘플 및 공부한 내용을 정리함.

- Files 클래스를 활용함으로써, Input/Output Stream 객체 생성의 코드가 많이 줄어듬.

 

- 샘플 소스 내용

1. 수신 폴더에 확장자 OK 파일 확인

2. 확장자 OK 파일을 읽어서 업무처리

3. 업무처리 후 파일 백업

- 확장자 샘플은 자바 버전 1.8 이상.

 

package sample;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.stream.Collectors;

public class NioFilesSample {

	public static void filesTest() throws IOException {

		// 기존의 File 클래스로 된것을 toPath() 메서드로 변경하여 사용할수도 있음.
		//File recvFile = new File( "/test_recv" );
		//File backFile = new File( "/test_back" );
		//Path recvPath = recvFile.toPath();
		//Path backPath = backFile.toPath();

		Path recvPath = Paths.get( "/test_recv" );
		Path backPath = Paths.get( "/test_back" );
		String ext = ".OK";

		// 확장자 OK 파일 찾기
		// Files.list -> Stream<Path>
		// Stream<Path> filter 기능으로 확장자 가져오기
		// filter 시에, Path 클래스의 endWith 함수는 경로별 마지막이며, 
		// String 으로 변환하여 문자열 endWith 를 사용해야함.
		List<Path> okPaths = Files.list( recvPath ).filter( p -> p.toString().endsWith( ext )).collect(Collectors.toList());
		for( Path okPath : okPaths ) {
			System.out.println("okPath[" + okPath + "] START");

			// Files.readAllLines
			// 캐릭터셋 부분은 Charset.forName("EUC-KR") or StandardCharsets 클래스활용할 수 있다.
			// StandardCharsets.UTF_8
			List<String> readLines = Files.readAllLines(okPath, Charset.forName("EUC-KR"));
			for( String readLine : readLines ) {

				// 파일 라인별 업무처리
				System.out.println( readLine );

			} // end for readLines

			// 파일 백업
			// LinkOption 은 리눅스에서 링크에 해당하는 부분이다.
			if( !Files.exists( backPath, LinkOption.NOFOLLOW_LINKS)) {
				Files.createDirectory( backPath );
			}

			String fileName = okPath.getFileName().toString();

			// resolve 는 backPath 경로에 덪붙인다. ( /test_back/fileName )
			Path backPath2 = backPath.resolve(fileName);

			// resolveSibling 는 okPath 현재경로의 부모경로부터 덪붙인다. ( /test_recv/fileName )
			Path backPath3 = okPath.resolveSibling(fileName);

			System.out.println("fileName[" + fileName + "]");
			System.out.println("backPath2[" + backPath2 + "]");
			System.out.println("backPath3[" + backPath3 + "]");

			// 파일이 병행처리될 경우, move 같은 경우는 오류가 많이 발생하니,
			// 복사/삭제처리로 안전성을 확보한다.
			//StandardCopyOption.ATOMIC_MOVE - move() 전용, 오류가 발생하더라도 파일이동을 보장한다.
			//StandardCopyOption.COPY_ATTRIBUTES
			//StandardCopyOption.REPLACE_EXISTING
			//Files.move( okPath, backPath2, StandardCopyOption.ATOMIC_MOVE);
			Files.copy( okPath, backPath2, StandardCopyOption.REPLACE_EXISTING);
			Files.deleteIfExists( okPath ); // deleteIfExists 존재하면 삭제

		} // end for okPaths
	}

	public static void main(String...strings) throws Exception {

		long startTime = System.currentTimeMillis();
		NioFilesSample.filesTest();
		long endTime = System.currentTimeMillis();
		System.out.println("[처리시간]" + (endTime - startTime));

	}
}

 

- 테스트 전

 

test_recv 폴더

 

- 결과

 

결과

 

반응형