파일 생성
1. io 패키지에 file20 클래스를 public static void main을 체크해서 만든다.
2. D 드라이브에 'user' 폴더와 'ftp' 폴더를 만든다.
- 파일을 만드는 방법을 모른다면 해당 글을 참고한다.
응용 문제
Q. 다음 조건에 맞는 코드를 작성하시오.
user라는 디렉토리에 이미지 5개가 있습니다.
ftp라는 디렉토리에 해당 이미지를 복사합니다.
단, 2MB(2097152) 이상 되는 이미지는 복사하지 않습니다.
또한 이미지 파일 명을 다음과 같이 저장되도록 셋팅합니다.
cdn_0.속성명
cdn_1.속성명
cdn_2.속성명
cdn_3.속성명
A1.
String url = "D:\\user\\"; // 원본 이미지가 있는 디렉토리
String url2 = "D:\\ftp\\"; // 복사한 이미지가 저장될 디렉토리
try {
File f = new File(url);
File allfile[] = f.listFiles(); // 해당 디렉토리에 모든 파일을 원시 배열로 변환
// System.out.println(Arrays.asList(allfile));
int w = 0;
while(w < allfile.length) {
FileInputStream is = new FileInputStream(allfile[w]);
if(is.available() < 2097152) {
byte[] by = new byte[is.available()];
is.read(by);
int n = String.valueOf(allfile[w]).lastIndexOf(".");
String rename="";
int ww = 0;
while(ww < w) {
rename = "cdn_" + ww + String.valueOf(allfile[w]).substring(n);
ww++;
}
System.out.println(rename);
FileOutputStream fs = new FileOutputStream(url2 + rename);
fs.write(by);
fs.flush();
fs.close();
is.close();
}
w++;
}
System.out.println("모든 파일을 정상적으로 복사하였습니다.");
}
catch(Exception e) {
System.out.println("디렉토리가 올바르지 않습니다.");
}
A2.
public class file20 {
public static void main(String[] args) {
new upload();
}
}
class upload{
String dir1 = "D:\\user\\"; // 원본 디렉토리
String dir2 = "D:\\ftp\\"; // 이미지를 복사하는 위치 디렉토리
FileInputStream fs = null; // 해당 파일을 로드 (read)
FileOutputStream os = null; // 해당 파일을 저장 (copy 및 save)
byte[] file = null; // 해당 파일의 크기를 byte로 분할하여 배열화
File arr[] = null; // 원본 디렉토리의 파일 리스트를 저장하는 배열
Integer limit_size = 2097152; // 파일 용량 제한 크기 (byte)
public upload() {
this.copyfile();
}
private void copyfile() {
File f = new File(this.dir1); // 해당 디렉토리를 호출
// File f2 = new File(this.dir2); // File : 파일 크기, 디렉토리 생성, 디렉토리 삭제시에 사용
this.arr = f.listFiles(); // 해당 디렉토리에 파일을 모두 원시배열로 전환
// ArrayList<File> as = new ArrayList<File>();
int w = 0; // 파일명을 0부터 순서대로 적용하기 위한 변수
try{
for(File filenm : this.arr) {
this.fs = new FileInputStream(filenm);
if(this.fs.available() <= this.limit_size) {
// 파일을 어떤 형태로 구분하여 로드 상황을 구성 (나눌건지, 전체를 읽을건지)
this.file = new byte[this.fs.available()];
this.fs.read(this.file);
// 파일 속성 타입 . 기준으로 가져옴 => 예시) .png, .jpeg
int n = String.valueOf(filenm).lastIndexOf(".");
String rename = "cdn_" + w + String.valueOf(filenm).substring(n);
// 해당 원본 파일을 이름 변경하여 ftp 디렉토리에 복사
this.os = new FileOutputStream(this.dir2 + rename);
this.os.write(file);
this.os.flush();
this.os.close();
w++; // 해당 조건에 맞을 경우 +1씩 증가하여 파일명에 순차적으로 적용
}
this.fs.close(); // 해당 조건과는 관계 없이 해당 파일을 종료
}
System.out.println("2MB 이하의 이미지를 모두 복사 완료 하였습니다.");
}
catch(Exception e) {
System.out.println("해당 경로 및 파일을 확인해 주시길 바랍니다!!");
}
}
}
이미지 확장자
- .png
- .bmp
- .jpg
- .jpeg
- .gif
- .webp
동영상 확장자
- .avi
- .mpeg4
- .webm
- .mp4
- .mov