본문 바로가기

Backend/Spring

자바 파일 복사 (+ Spring)

Java에서 파일을 복사하는 코드에요.

Java

기존 java.io

 

File in = new File("C:\\Temp\\abc.txt");
File out = new File("C:\\Temp\\def.txt");

try (InputStream fis = new FileInputStream(in); OutputStream fos = new FileOutputStream(out)) {
	int bytesRead = 0;
	while ((bytesRead = fis.read()) != -1) {
		fos.write(bytesRead);
	}
	fos.flush();
} catch (Exception e) {
	e.printStackTrace();
}

 

java.nio

 

Path in = Paths.get("C:\\Temp\\abc.txt");
Path out = Paths.get("C:\\Temp\\def.txt");
Files.copy(in, out);

Spring Framework

File in = new File("C:\\Temp\\abc.txt");
File out = new File("C:\\Temp\\def.txt");
FileCopyUtils.copy(in, out);