13일차 : IO, File클래스, 내부클래스, 객체의 직렬화, 재귀메소드
File클래스 - 디렉토리 확인 및 디렉토리 삭제, 생성
/* << File클래스★ >> - 파일 또는 디렉토리에 관련된 정보를 갖는 클래스 */ import java.io.*; class File01{ public static void main(String[] args) { File f=new File("c:\\JAVA\\12일차\\navi.jpg"); //public boolean exists() if(f.exists()){ System.out.println("디렉토리가 존재합니다."); System.out.println("파일의 크기: "+f.length() + "bytes"); //해당 파일의 크기 }else{ System.out.println("해당 디렉토리가 존재하지 않습니다."); } File f1=new File("c:\\JAVA\\test"); if(f1.exists()){ f1.delete();//디렉토리 또는 파일 삭제하기(디렉토리 안에 파일이 있으면 디렉토리를 지울 수 없으며 그 안의 내용을 지워줘야 삭제가능) System.out.println("해당 디렉토리를 삭제했습니다."); }else{ System.out.println("해당 디렉토리가 존재하지 않습니다."); f1.mkdir();//디렉토리 생성하기 System.out.println("해당 디렉토리를 생성했습니다."); } } }
File클래스 - 디렉토리 안의 목록(디렉토리명 또는 파일명)이름을 배열로 얻어오기
import java.io.*; class File02 { public static void main(String[] args) { File f=new File("c:\\JAVA"); //public string[] list() //디렉토리 안의 목록(디렉토리명 또는 파일명)이름을 배열로 얻어오기 String[] list=f.list(); for(int i=0; i<list.length; i++){ System.out.println(list[i]); } System.out.println("======================================="); //public File[] listFiles() //디렉토리 안의 정보를 File객체 배열로 얻어옴 File[] flist=f.listFiles(); for(int i=0; i<flist.length; i++){ if(flist[i].isDirectory()){ System.out.println("디렉토리: "+flist[i]); }else if(flist[i].isFile()){ System.out.println("파일: "+flist[i] + "파일 크기: "+flist[i].length() + "bytes"); } } } }
File클래스 - 파일 절대 경로 및 이름 불러오기
import java.io.*; class File03 { public static void main(String[] args) { File f=new File("c:\\aa\\bb"); if(f.exists()){ System.out.println("디렉토리가 존재해요."); }else{ f.mkdirs(); //자식 디렉토리까지 생성 System.out.println("디렉토리 생성"); } File f1=new File("File01.java"); //public string getAbsolutePath() ==> 파일의 절대 경로 얻어오기 String path=f1.getAbsolutePath(); System.out.println("파일의 절대 경로: "+path); String name=f1.getName(); //getName : 파일 이름 불러오기 System.out.println("파일명: "+name); } }
내부클래스 - 인스턴스 내부 클래스class Rect{ private int x, y; private String color; public Rect(int x, int y, String color){ this.x=x; this.y=y; this.color=color; } public void print(){ Printer prn=new Printer(); prn.printRect(); } //인스턴스 내부 클래스 class Printer{ public void printRect(){ //Outer클래스(Rect)의 비공개 멤버 변수에 접근 가능하다. System.out.println(x+"," +y+"의 위치에 "+color+"색상으로 사각형 출력하기"); } } } class InnerClass01{ public static void main(String[] args) { Rect rr=new Rect(100, 200, "red"); rr.print(); } }
내부 클래스 - 익명의 내부 클래스
//익명의 내부 클래스 interface Shape{ void draw(); } class InnerClass02{ public static void main(String[] args) { /*class MyRect implements Shape{//MyRect가 딱 한번만 호출하기 위한 목적으로 만들어진다. 1회용! public void draw(){ System.out.println("사각형 그리기"); } } MyRect rr=new MyRect(); rr.draw(); */ //위의 작업을 익명의 내부클래스로 만들면(일회성 클래스인 경우에) /*Shape rect=new Shape(){ //new할 수 없지만 다시 블럭을 지정, 추상메소드 작성 public void draw(){ System.out.println("사각형 그리기"); } }; rect.draw(); } }*/ new Shape(){ public void draw(){ System.out.println("사각형 그리기"); } }.draw(); } }
객체의 직렬화
//MyPerson.java import java.io.Serializable; /* << 객체의 직렬화 >> - 객체를 바이트 단위로 일렬로 나열하는 것 - 직렬화가 가능하도록 하려면 Sserializable인터페이스를 상속받는다. - 멤버가 transient인 경우, static인 경우는 직렬화가 되지 않는다. #역직렬화 - 바이트 단위로 나열된 데이터를 다시 조합해 객체로 만드는 것 */ //직렬화가 가능한 클래스 만들기 public class MyPerson implements Serializable{ private String name; //이름 private transient String jumin; //주민번호--> 직렬화가 되지 않는 멤버 transient: 멤버 앞에 주면 직렬화 되지 않도록 하는 것 private String phone; //전화번호 public MyPerson(String name, String jumin, String phone){ this.name=name; this.jumin=jumin; this.phone=phone; } public String getName(){return name;} public String getJumin(){return jumin;} public String getPhone(){return phone;} }
ObjectOutputStream01 - 객체를 파일로 저장하기 위한 스트림 객체 생성
import java.io.*; import java.util.Date; /* ObjectOutputStream ==> 객체를 출력하기 위한 스트림 ObjectInputStream ==> 객체를 읽어오기 위한 스트림 */ class ObjectOutputStream01 { public static void main(String[] args) { //public ObjectOutputStream(OutputStream out) throws IOException //객체를 파일로 저장하기 위한 스트림 객체 생성 try{ //객체를 파일로 저장하기 위한 스트림 객체 생성 ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("test.ser")); //public final void writeObject(Object obj) throws IOException //객체를 파일로 저장하기 oos.writeObject(new String("안녕")); oos.writeObject(new Date()); oos.writeObject(new Integer(100)); oos.close(); System.out.println("파일로 저장 성공!"); }catch(IOException ie){ System.out.println(ie.getMessage()); } } }
ObjectInputStream02 - 파일에 저장된 순서로 객체 읽어오기
import java.util.Date; import java.io.*; class ObjectInputStream02 { public static void main(String[] args) { try{ //객체를 파일에서 읽어오기 위한 스트림 객체 ObjectInputStream ois=new ObjectInputStream(new FileInputStream("test.ser")); //public final Object readObject() throws IOException, ClassNotFoundException //파일에 저장된 순서로 객체 읽어오기 String str=(String)ois.readObject(); Date d=(Date)ois.readObject(); Integer i=(Integer)ois.readObject(); System.out.println("파일에 저장된 객체"); //파일에서 읽어오노 객체를 화면에 출력 System.out.println(str); System.out.println(d); System.out.println(i); ois.close(); //스트림 닫기 }catch(IOException ie){ System.out.println(ie.getMessage()); }catch(ClassNotFoundException ce){ System.out.println(ce.getMessage()); } } } /* 파일에 저장된 객체 안녕 Wed Aug 01 10:17:07 KST 2012 100 */
ObjectOutputStream03 - 객체를 파일로 저장하고 예외발생처리
import java.io.*; class ObjectOutputStream03 { public static void main(String[] args) { try{ ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("person.ser")); out.writeObject(new MyPerson("홍길동", "8012122223456", "010-111-1234")); out.close(); System.out.println("객체를 파일로 저장 성공!"); }catch(IOException ie){ System.out.println("예외발생:"+ie.getMessage()); } } }
ObjectInputStream04 - person.per에 저장된 객체를 읽어와 화면에 출력
import java.io.*; class ObjectInputStream04 { public static void main(String[] args) { //person.per에 저장된 객체를 읽어와 화면에 출력해 보세요. try{ ObjectInputStream ois=new ObjectInputStream(new FileInputStream("Person.ser")); //파일에서 객체 읽어오기 MyPerson per=(MyPerson)ois.readObject(); //리턴타입이 오브젝트니까 형변환 꼭 해서 메소드 통해 얻어옴. System.out.println("Person에 있는 내용 출력하기"); System.out.println("이름: "+per.getName()); System.out.println("주민번호: "+per.getJumin()); System.out.println("전화번호: "+per.getPhone()); ois.close(); //스트림 닫기 }catch(IOException ie){ System.out.println(ie.getMessage()); }catch(ClassNotFoundException ce){ System.out.println(ce.getMessage()); } } } /* [결과] Person에 있는 내용 출력하기 이름: 홍길동 주민번호: null 전화번호: 010-111-1234 */
재귀 메소드 - 팩토리얼 구하기
//재귀메소드 - 자기 자신을 호출하는 메소드 class Test07_재귀메소드{ public static void main(String[] args) { int n=4; int num=factorial(n); System.out.println(n+"!="+num); //4!=4x3x2x1 } public static int factorial (int n){ return (n>1)?n*factorial(n-1):n; } }
Quiz01
/* c:\\JAVA\\test 폴더를 삭제해 보세요! */ import java.io.*; class Quiz01 { public static void main(String[] args) { File f=new File("c:\\JAVA\\test"); if(f.exists()){ //디렉토리 안의 목록(디렉토리또는파일) 얻어오기 File[]flist=f.listFiles(); //디렉토리 안의 파일 지우기 for(int i=0; i<flist.length; i++){ System.out.println("디렉토리: "+flist[i]); flist[i].delete(); } f.delete(); //디렉토리 삭제하기 System.out.println("해당 디렉토리를 삭제했습니다."); }else{ System.out.println("해당 디렉토리가 존재하지 않습니다."); f.mkdir(); //디렉토리 생성하기 System.out.println("해당 디렉토리를 생성했습니다."); } } }
Quiz02
/*
디렉토리 삭제하기 - 폴더 안에 또 폴더가 존재하는 경우
*/
import java.io.*;
class Quiz02 {
public static void main(String[] args) {
File f=new File("c:\\java\\test");
if(delDir(f)){
System.out.println("디렉토리 삭제 성공");
}else{
System.out.println("디렉토리 삭제 실패");
}
}
//재귀메소드 호출
public static boolean delDir(File f){
File[] list=f.listFiles(); //디렉토리 안의 목록 얻어오기
for(int i=0; i<list.length; i++){
if(list[i].isFile()){//파일인 경우
list[i].delete();//파일 삭제하기
}else{ //디렉토리인 경우
delDir(list[i]);//디렉토리 안의 목록 삭제하는 자기 자신의 메소드 호출
}
}
if(f.delete()){//자기 자신의 폴더 삭제하기
return true;//정상적으로 삭제됐으면 true, 아니면 false
}else{
return false;
}
}
} Quiz03 Quiz04 Quiz05
/*
디렉토리의 크기를 구하는 프로그램 작성
1.쉬운경우:디렉토리안에 파일만 존재하는 경우
2.어려운경우:디렉토리안에 디렉토리가 존재하는 경우
*/
//1번
import java.io.*;
class Quiz03{
public static void main(String[] args) {
File f=new File("c:\\java\\test");
long fileSize=0;
File[] list=f.listFiles();
for(int i=0;i<list.length;i++){
fileSize+=list[i].length();
}
System.out.println("디렉토리 크기:"+fileSize +"bytes");
}
}
//2번
import java.io.*;
class Quiz04 {
public static void main(String[] args) {
File f=new File("c:\\java\\test");
long dirSize=getDirSize(f);
System.out.println("디렉토리크기: "+dirSize + "bytes");
}
public static long getDirSize(File f){
long size=0; //디렉토리 크기
File[] list=f.listFiles();
for(int i=0; i<list.length; i++){
if(list[i].isFile()){ //파일인 경우
size+=list[i].length(); //파일크기를 구해서 디렉토리 크기에 누적
}else{ //디렉토리인 경우
size+=getDirSize(list[i]); //자식 디렉토리크기 구해서 디렉토리 크기에 누적
}
}
return size;
}
}
interface Animal{
void move();
void say();
}
class Quiz05 {
public static void main(String[] args) {
//위의 인터페이스를 이용해서 익명의 내부클래스를 만들어 아래처럼
//결과가 나오도록 출력해 보세요.
//고양이는 살금살금
//고양이는 야옹야옹
Animal rr=new Animal(){
public void move(){
System.out.println("고양이는 살금살금");
}
public void say(){
System.out.println("고양이는 야옹야옹");
}
};
rr.move();
rr.say();
}
}
[ 과 제 ]
'JAVA 기초' 카테고리의 다른 글
15일차 : 스레드의 동기화 (0) | 2012.08.12 |
---|---|
14일차 : 스레드(Thread) (0) | 2012.08.12 |
12일차 : IO, 입출력 (0) | 2012.08.12 |
11일차 : 예외처리, IO(InputStream,OutputStream), 패키지 만들기 (0) | 2012.08.12 |
10일차 : 확장for문, 제네릭, Calendar 클래스, map, 자바의 컬렉션 프레임워크 (0) | 2012.08.12 |