2011. 1. 11. 15:59
[핵심정리]!!!
!프로그램을 기준으로
① Source => 입력처리 스트림
   Destination -> 출력처리 스트림


② 처리되는 단위
    - byte(1byte) : byte 스트림
    - char(2byte) : char 스트림

③ 타겟으로부터 직접 읽거나/쓰는 스트림 => Node Stream
    -노드 스트림 객체는 반드시 하나 이상 있어야 한다.
    -노드 객체를 만드는 것은 파일 open을 의미
     노드가 될 수 있는 것 : File, 메모리(Array, Stream), pipe, socket
     [노드스트림] : 노드에 직접 연결되어 있는 스트림을 의미
     char : FileReader / FileWriter
     byte : FileInpuStream / FileOutputStream

④ 타겟으로부터 직접 읽거나/쓰는 것이 아닌 스트림 => Filter 스트림
 (중간처리는 모두 Filter 스트림이 함)







1. 자바 I/O 스트림 소개
 1) 스트림(Stream)이란?
    데이터의 순차적 흐름을 의미
    - 데이터가 출발하는 출발지 또는 근원지(Source)가 있다면 데이터가 도착하는 종착지(Destination)가 있습니다.
    - 데이터의 출발지와 종착지 사이의 데이터의 흐름을 스트림이라고 부릅니다.

 3)스트림 분류
java.io 패키지는 데이터를 읽고 쓰기 위해 필요한 스트링 클래스들을 모아놓고 있습니다.
 * 바이트스트림 : 주로 binary데이터를 처리  * 문자스트림: 주로 문자를 처리
 입출력 작업 단위 : 8비트
제공되는 API :  InputStream/OutputStream 계열
사용되는 경우 : 이미지 오디오와 같은 바이너리 데이터를 입출력 하고자 할 때
입출력 작업 단위 : 16비트
제공되는 API : Reader /Writer 계열
사용되는 경우 : 텍스트 데이터를 입출력 하고자 할 때 
- 대부분의 프로그램은 텍스트 데이터를 읽고 쓸 때 reader와 writer을 씁니다.



1)노드스트림

문자스트림

바이트스트림

파일

FileReader

FileWriter

FileInputStream

FileOutPutStream

메모리 : 배열

CharArrayReader

CharArrayWriter

ByteArrayInputStream

ByteArrayOutputStream

메모리 : 스트림

StringReader

StringWriter

파이프

PipedReader

PipedWriter

PipedInputStream

PipedOutputStream



2. 필터스트림: 가공하는 작업을 하는 스트림(0개 이상)
                     필요하면 집어 넣어 쓰세요.
  필터 스트림은 프로세싱 스트림이라고 함
  특정 기능을 수행하거나 그런 기능을 갖고 있는 메소드를 사용하기 위해서 기존 스트림을 감싸는 역할을 하는 스트림



File 클래스
File객체는 실제로 파일을 오픈하는 것이 아니고, 체크하는 작업을 한다.
(파일에 대한 정보를 보는 클래스)
File file = new File("파일명");
File file = new File("디렉토리명", "파일명");

import java.io.File;
import java.io.IOException;
public class FileTest {
 public static void main(String[] args) {
  File file = new File("c:/data/test.txt");
  System.out.println("파일명 : " + file.getName());
  System.out.println("파일 절대 경로 : " + file.getAbsolutePath());
  System.out.println("파일size : " + file.length());
  if( file.canExecute())
   System.out.println("실행할  수 있다.");
  if( file.canRead())
   System.out.println("읽을 수 있다.");
  if( file.canWrite())
   System.out.println("쓸 수 있다.");
  
  File file2 = new File("c:/data/hello.txt");
  if( file2.exists())
   System.out.println("파일이 존재합니다.");
  else{
   System.out.println("파일이 존재하지 않습니다");
   try {
    if(file2.createNewFile())
     System.out.println("파일이 성공적으로 생성하였습니다.");
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } 
 }
}
[console]
파일명 : test.txt
파일 절대 경로 : c:\data\test.txt
파일size : 62
실행할  수 있다.
읽을 수 있다.
쓸 수 있다.
파일이 존재합니다.






FileReader/FileWriter 클래스

∎FileReader/FileWriter는 반드시 Exception처리를 해 주어야 한다.
∎FileReader객체와 FileWriter객체를 생성해 주었다면, 반드시 close시켜주어야 한다.

<Reader의 메소드>
* int read() 
 : 입력소스로부터 하나의 문자를 읽어 온다. char의 범위인  0~65535범위의 정수를 반환하며, 입력스트림의 마지막 데이터에 도달하면, -1을 반환한다.

* int read(char[] c)
: 입력소스로부터 매개변수로 주어진 배열 c의 크기만큼 읽어서 배열 c에 저장한다. 읽어 온 데이터의 개수 또는 -1을 반환한다..

*abstract void closd()
: 입력 스트림을 닫음으로써 사용하고 있던 자원을 반환한다.

<Writer의 메서드>
* void write(int b)
: 주어진 값을 출력  소스에 쓴다.

* abstract void close()
: 출력스트림을 닫음으로써 사용하고 있던 자원을 반환한다.

* abstract void flush()
: 스트림의 버퍼에 있는 모든 내용을 출력소스에 쓴다.(버퍼가 있는 스트림에만 해당됨)

 

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadTest {
 public static void main(String[] args) {
  File file = new File("c:/data/test.txt");
  FileReader in = null;
  FileWriter out = null;
  try {
   in = new FileReader(file);
   out = new FileWriter("c:/data/test.backup.txt");
   int ch = 0;
   while( (ch = in.read()) != -1)
    out.write(ch);
   
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(in != null) try { in.close();} catch (IOException e) {e.printStackTrace();}
   if(out != null) try { out.close();} catch (IOException e) {e.printStackTrace();}
  }
 }
}

 




Copy클래스 만들기.. java simple.syeong.ch13.Copy args[0] args[1]







BufferedReader/BufferedWriter
라인단위로 읽고 쓰는 필터 스트림


public class Copy {
 public static void main(String[] args) {
  if( args.length < 2){
   System.out.println("사용법 : java simple.syeong.ch13.Copy args[0] args[1]");
   System.exit(2);
   //argument에러는 2로 처리.
   
  }
  
  File sfile = new File(args[0]);
  File tfile = new File(args[1]);
  
  if(! sfile.canRead()){
   System.out.println(args[0] + "파일은 읽을 수 없습니다.");
   System.exit(1);
   //error코드로 처리
  }
  
  if( tfile.exists()){
   System.out.println(args[1] + "이미 존재하는 파일입니다.");
   System.exit(1);
  }
  
  FileReader in = null; //입력노드스트림
  FileWriter out = null; //출력노드스트림
  BufferedReader br = null; //라인 단위로 읽을 수 있는 필터스트림
  BufferedWriter bw = null; //라인 단위로 쓸 수 있는 필터스트림
  
  try {
   //FileReader in = new FileReader(new File("c:/data/test.txt"));
   in = new FileReader(sfile); //char단위로 파일에서 읽기
   out = new FileWriter(tfile); //char단위로 파일에서 쓰기.
   br = new BufferedReader(in);
   bw = new BufferedWriter(out);
   String line = null;
   while( (line = br.readLine()) != null){
    bw.write(line);
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(in != null) try { in.close();} catch (IOException e) {e.printStackTrace();}
   if(out != null) try { out.close();} catch (IOException e) {e.printStackTrace();}
  }
 }
  
}
위의 코드는 약간의 문제가 있다.
쓸데 없는 로컬변수는 in과 out을 썼기 때문이다. 이경우 코드를 다음과 같이 고쳐조는 것이 좋다.
public class Copy {
 public static void main(String[] args) {
  if( args.length < 2){
   System.out.println("사용법 : java simple.syeong.ch13.Copy args[0] args[1]");
   System.exit(2);
   //argument에러는 2로 처리.
   
  }
  
  File sfile = new File(args[0]);
  File tfile = new File(args[1]);
  
  if(! sfile.canRead()){
   System.out.println(args[0] + "파일은 읽을 수 없습니다.");
   System.exit(1);
   //error코드로 처리
  }
  
  if( tfile.exists()){
   System.out.println(args[1] + "이미 존재하는 파일입니다.");
   System.exit(1);
  }
  
  //FileReader in = null; //입력노드스트림
  //FileWriter out = null; //출력노드스트림
  BufferedReader br = null; //라인 단위로 읽을 수 있는 필터스트림
  BufferedWriter bw = null; //라인 단위로 쓸 수 있는 필터스트림
  
  try {
   //FileReader in = new FileReader(new File("c:/data/test.txt"));
   //in = new FileReader(sfile); //char단위로 파일에서 읽기
   //out = new FileWriter(tfile); //char단위로 파일에서 쓰기.
   br = new BufferedReader(new FileReader(sfile));
   bw = new BufferedWriter(new FileWriter(tfile));
   String line = null;
   while( (line = br.readLine()) != null){
    bw.write(line);
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   if(br != null) try { br.close();} catch (IOException e) {e.printStackTrace();}
   if(bw != null) try { bw.close();} catch (IOException e) {e.printStackTrace();}
  }
 }
  
}





1.파일 객체를 생성합니다.
  File = fi = new File("a.txt");

2.FileInputStream 객체를 생성합니다.
  FileInputStream fi = new FileInputStream(file)

3. InputStreamReader (1바이트씩 들어오는 데이터를 2바이트로 묶는..)
   InputStreamReader isr = new InputStreamReader(fi);

4. BufferedReader 객체를 생성합니다.(line단위로 읽는)
   Buffered br = new BufferedReader(isr)

5. 파일에서 데이터를 읽음
(콘솔에서는 입출력이 byte이기에 이러한 작업을 함)









'Java' 카테고리의 다른 글

표현언어(Expression Language)  (0) 2011.01.27
java.util 패키지(유틸리티 API)  (0) 2011.01.11
static정리  (0) 2011.01.06
추상클래스 / 인터페이스  (0) 2011.01.06
instanceof연산자  (0) 2011.01.05
Posted by Triany
2011. 1. 11. 13:45

java.util 패키지는 사용자 프로그램에서 필요로 하는 편리한 기능들을 모아 둔 클래스들의 모임이다.

Date클래스
: Date 클래스는 날짜와 시간에 관한 정보를 표현한다.
그러나 JDK의 버전이 향상되면서 deprecate되는 메서드들이 많다.
Date보다는 Calendar클래스를 더 권장.





Calendar클래스(추상클래스)
Calendar 클래스도 Date클래스처럼 날짜와 시간에 관한 정보를 표혈할 때 사용한다.(Calendar클래스를 Date클래스보다 더 권장)
⊙Calendar 클래스는 추상 클래스로 생성자를 제공하지 않는다.
   - 따라서 Calendar 클래스의 객체를 생성하기 위해 new 연산자를 사용할 수 없다. 
  - 추상 클래스이므로 객체를 직접 생성할 수 없지만, 
     getInstance() 메서드를 이용하여 시스템의 날짜와 시간의 객체를 얻어올 수 있다
.

int get(int field)
//날짜에서 표현할 수 있는 값은 다 상수값으로 제공
//calendar 클래스는 날짜와 시간 표현을 위해 다양한 상수를 제공하고 있다.







'Java' 카테고리의 다른 글

표현언어(Expression Language)  (0) 2011.01.27
파일과 입출력 API  (0) 2011.01.11
static정리  (0) 2011.01.06
추상클래스 / 인터페이스  (0) 2011.01.06
instanceof연산자  (0) 2011.01.05
Posted by Triany
2011. 1. 6. 09:33

<객체와 상관 없이!! 객체 생성 이전에 로드되는!!>
-static  멤버들을 객체의 생성 없이 호출할 수 있는 것은 객체 생성 이전에 메모리가 할당되기 때문입니다.
-즉 객체 생성 이전에 클래스 로더에 의해 클래스가 로딩될 때 메모리에 올라가기 때문에 객체를 만들기 전에 클래스 이름만으로도 호출이 가능합니다.

그렇기 때문에 이미 메모리에 올라간 static 멤버가 아직 메모리에 올라가지 않은, static이 아닌 멤버를 호출하는 것은 불가능하다.


  ex)  Class A{
             int a; //
             static int c; //클래스 변수
             static void abc(){
                    int b = a;
             }  //Error! 불가능.
         }
ex)
System.out.println()  //System클래스에 있는 out이라는 객체를 가져와서, out이라는 객체의 println()이라는 함수를 쓰겠다.


1, static 메서드 - static 변수 OK
                         클래스 멤버변수 X

2. 클래스 멤버 메서드 - static 변수 OK
                                 class 멤버 변수 O.K


<static 키워드의 정리>

1. static 멤버는 클래스 변수, 클래스 메소드라고 불리웁니다.
2. 객체 생성없이 [클래스이름.멤버이름]으로 static 멤버를 호출할 수 있습니다.
3. 그 클래스로부터 만들어진 모든 객체들이 static 멤버를 공유합니다.
4. static 멤버는 객체 생성 이전에 클래스가 로딩될 때, 메모리에 먼저 올라갑니다.
5. static 멤버는 static이 아닌 멤버를 직접 호출할 수 없습니다.
6. this와 함께 쓰일 수 없습니다.
7. 부모 클래스의 static 메소드는 메소드 오버라이딩이 안됩니다.



main() 메소드
main()메소드가 static으로 정의되어져야 하는 이유
main()메소드는 JVM이 프로그램을 시작하는 시작점이기 때문에 main()을 가지고 있는 클래스가 객체를 생성하는 것과 상관없이 무조건 실행되어야 하기 때문입니다.

main()메소드의 접근 지정자가 public 인 이유
클래스가 어느 위치에 있건 간에 JVM에서 접근하려면 가장 넓은 범위의 접근 범위를 설정해야 하기 때문입니다.


static 이니셜라이저(Initializer)

static 이니셜라이저(Initializer)란, 메소드 바깥 쪽에 다음과 같은 형태로 static 코드 블록을 만드는 것을 의미합니다.

 public class MyClass {
   static {
      
   }
   //멤버 변수 정의
   //멤버 메소드 정의
}
 - static 코드 블록 안의 코드는 클래스가 로딩될 때 단 한번만 실됩니다.
-  static형식으로 초기화 됨.


'Java' 카테고리의 다른 글

표현언어(Expression Language)  (0) 2011.01.27
파일과 입출력 API  (0) 2011.01.11
java.util 패키지(유틸리티 API)  (0) 2011.01.11
추상클래스 / 인터페이스  (0) 2011.01.06
instanceof연산자  (0) 2011.01.05
Posted by Triany