반응형

문제

C:\temp에 있는 .txt 파일만 삭제하는 프로그램을 작성하라. C:\나 C:\wingdows 등의 디렉터리에 적용하면 중요한 파일이 삭제될 수 있으니 조심하라.

 

출력 예시

C:\temp디렉터리의 .txt 파일의 모두 삭제합니다....
C:\temp\p.txt 삭제
C:\temp\phone.txt 삭제
C:\temp\test.txt 삭제
총 3개의 .txt 파일을 삭제하였습니다.

 

소스 코드

import java.io.*;

public class Main9 {
	public static void DeleteFile(File temp) {
		File[] subFiles = temp.listFiles();
		int count=0;
		System.out.println("C:\\temp디렉터리의 .txt 파일의 모두 삭제합니다....");
		for(int i = 0;i<subFiles.length;i++)
		{
			String name = subFiles[i].getName();
			int index = name.lastIndexOf(".txt");
			if(index != -1)
			{
				subFiles[i].delete();
				count++;
				System.out.println("총 "+count+"개의 .txt파일을 삭제하였습니다.");
			}
		}
	}
	public static void main(String[] args) {
		File f = new File("파일경로");
		DeleteFile(f);
	}

}
반응형
반응형

문제

File 클래스를 이용하여 C:\에 있는 파일 중에서 제일 큰 파일의 이름과 크기를 출력하라.

 

출력 예시

가장 큰 파일은 C:\hiberfil.sys 3394002944바이트

 

소스 코드

import java.io.File;

public class Main8 {
	public static void MaxByteFile(File dir) {
		File[] subFiles = dir.listFiles();
		int Max = 0;
		File MAX = null;
		for(int i = 0;i<subFiles.length;i++)
		{
			File temp = subFiles[i];
			if(Max < temp.length()) {
				Max = (int)temp.length();
				MAX = temp;
			}			
		}
		System.out.println("가장 큰 파일은"+MAX.getPath()+" "+ Max + "바이트");
	}
	public static void main(String[] args) {
		File f = new File("C:\\");
		MaxByteFile(f);
	}

}
반응형
반응형

문제

파일 복사 연습을 해보자. 이미지 복사가 진행하는 동안 10% 진행할 때마다 '*' 하나씩 출력하도록 하라. 아래 예시는 프로젝트 폴더 밑에 a.jpg을 미리 준비해두었다.

 

출력 예시

a.jpg를 b.jpg로 복사합니다.
10%마다 *를 출력합니다.
**********

 

소스 코드

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

public class Main7 {

	public static void main(String[] args) {
		File src = new File("파일경로\\a.jfif");
		File dest = new File("파일경로\\b.jfif");
		int c;
		int count = 0,div = 1;
		try {
			FileInputStream fi = new FileInputStream(src);
			FileOutputStream fo = new FileOutputStream(dest);
			System.out.println(src.getPath() + "를 "+ dest.getPath()+"로 복사합니다");
			System.out.println("10%마다 *를 출력합니다");
			while((c=fi.read())!=-1) {
				fo.write((byte)c);
				count++;
				if(((src.length())/10*div ) == count ) {
					System.out.print("*");
					div++;
				}
			}
			fi.close();
			fo.close();
			
		}catch(IOException e) {
			System.out.println("파일 복사 오류");
		}
	}

}

jpg가 아닌 jfif그림파일을 사용했습니다.

 

a.jfif
0.02MB
b.jfif
0.02MB

반응형

+ Recent posts