package test ;
public class Example {
public static void main(String[] args )
{
File m_dir = new File("morph");
//m_dir 객체에 morph 디렉토리 연결
File m_files[] = m_dir.listFiles();
// listFiles 메소드를 사용하면 하위 파일들 가져올 수 있다.
fo(int i = 0 ; i < m_files.length ; ++i) {
System.out.println(i + "번째 파일 명 : " + m_files[i].getName());
//해당 디렉토리에서 하위 파일들을 가져올 수 있다.
}
}
}
2. 파일/ 디렉토리 생성과 삭제
파일을 생성하는 메소드 : createNewFile
File m_file = new File("house.txt");
try {
m_file.createNewFile();
} catch(IOException e ) {
e.printStackTrace();
}
//파일 생성은 입출력 쪽이기 때문에 "IOException 예외처리 반드시 필요
3. 디렉토리 생성 : mkdir 메소드
File m_dir = new File("program");
m_dir.mkdir();
4. 삭제는 파일이나 디렉토리나 똑같은 메소드 : delete
File m_dir = new File("program");
File m_file = new File("house.txt");
m_dir.delete();
m_file.delete();
//디렉토리를 삭제할 때 그 하위에 있는 파일이나 디렉토리도 다 지워진다.
5. FileReader(파일을 읽는 클래스), FileWriter(파일을 쓰는 클래스 )
try {
FileReader m_reader = new FileReader("test");
//파일명만 쓴 이유는 같은 위치에 있기 때문에
//다른 위치를 쓰고 싶다면 d:/D_Other/
System.out.println(String.valueOf(char)m_reader.read()));
m_reader.close();
}
1) 실제로 파일의 내용을 읽는 메소드는 "read" 메소드를 사용한다.
read() : 매개변수가 없는 "read메소드 " : 문자를 하나씩 읽어오는 메소드 .
여러개의 문자를 출력하려면 ? : "read()" 메소드를 반복문으로 여러번 호출하기
언제까지 반복해야 할까? : read 메소드는 문자열의 끝을 만나면 -1 을 리턴해준다.
전체문자 출력하기
File m_file = new File("test") ;
try {
FileReader m_reader = new FileReader (m_file);
//FileReader 는 파일을 읽는 클래스이다.
int c ;
while(true)
{
c = m_reader.read();
if( c== -1 )
break;
System.out.println(String.valueOf((char)c));
}
m_reader.close();
} catch(FileNotFoundException 2 ) {
}catch(IOException e ) {
}
* 참고 :
1) "FileNotFoundException 은 FileReader 클래스 객체를 생성할 때 해주어야 하는 예외처리로써 해당 경로에 파일이 없을 때 발생하는 예외.
2) String.valueOf는 문자열로 형변환하는 메소드
3) read 메소드의 리턴값은 정수형이다. 캐스트 연산자(char) 를 사용해주어 문자로 변경해 주는 모습. (자바에서는 유니코드 사용 )
6. 한꺼번에 파일 읽기 ( 매개변수가 있는 read() )
File m_file = new File("test");
//객체 생성
try {
FileReader m_reader = new FileReadeer(m_file);
//읽을 수 있도록 만들어줌
char[] char_array = new char[64];
//이건 배열을 그냥 만들어 주었고,
m_reader.read(char_array);
//이 배열에 읽는다. 원래 파일인 m_file 을 읽을 수 있도록 해주고, 거기서 읽어올건데, //char_array 라는 배열에 넣는것...?
System.out.println(String.valueOf(char_array_.trim());
//trim() 메소드는 String 메소드인데 현재 문자열에서 모든 빈칸 (띄어쓰기) 을 삭제해준다.
// 버퍼크기(char_array)가 충분히 해야한다. ( 글자를 다 넣어줄 수 있도록 )
m_reader.close();
} catch(FileNotFoundException e ) {
}catch (IOException e ) {
}
7. 2개의 숫자가 있는 버퍼
File m_file = new File("test") ;
try {
FileReader m_reader = new FileReader(m_file);
char[] char_array = new char[64];
m_reader.read(char_array, 5, 5);
System.out.print(String.valueOf(char_array));
m_reader.close();
} catch ~~~~
// m_reader.read(char_array, 5, 5) ; 에서 첫번째 5는 "offset"의미로 씌여질 버퍼의 시작위치.
앞에 5만큼의 길이가 비어 있다.
두번째 5는 읽어올 데이터의 길이이다. 즉 문자열을 읽어올 때 문자 5개를 읽어온다는 의미
8. FileReader 닫는 부분
FileReader 객체를 다 사용한 후에 닫아 주어야 한다.
FileReader 객체를 다 활용하면 반드시 닫아 주어야 하는데 닫지 않고 프로그램을 종료하게 되면 파일에 데이터가 다 씌여지기도 전에 손실이 일어날 수 도 있다.
9. 파일에 문자 쓰기 ( 파일에 쓸 수 있는 메소드 : write 메소드 )
try {]
FileWriter m_writer = new FileWriter ("test") ;
//FileWriter 클래스 객체를 생성. ( 전체 경로를 쓰거나, File 객체를 생성해서 넘겨줌)
char[] char_array = {'j', 'A', 'V', 'A'};
m_writer.write(char_array);
//문자열을 char 배열로 받는 메소드
m_writer.close();
} catch ( FileNotFoundException e ) {
} catch (IOException e ) {
}
: write 메소드의 사용 :
1. char 배열로 데이터를 받기
2. String 문자열로 데이터를 받기
3.int 정수형으로 받기 : 프로그래밍에서는 모든 문자가 숫자로 구성되어 있다.
1) String 문자열로 파일 쓰기
try {
FileWriter m_writer = new FileWriter("test");
String tmp_str = "Android & IOS";
m_writer.write(tmp_str); //String 문자열로 파일 쓰기
m_writer.close();
} catch (FileNotFoundException 2 ) {
}catch (IOException e )
2) 정수로 파일에 문자 쓰기
try {
FileWriter m_writer = new FileWriter("test");
m_writer.write(77);
m_writer.close() ;
} catch ~~~~
-> M자가쓰여진다. : 유니코드 77은 M자 이다.
3) 원하는 부분만 문자 쓰기
(write 메소드 중 오프셋과 길이가 있는 메소드 )
try {
FileWriter m_writer = new FileWriter("test") ;
String tmp_str = "Android & IOS";
m_writer.write(tmp_str,2.5);
m_writer.close();
}
catch ~
여기서 offset : 2 , length : 5 ; 저기 문자열중에서 2번째부터 5개만 (즉 6번째까지) 파일에 쓰겠다는 뜻. (char 배열도 동일 )
new
1. FileInputStream, FileOutputStream 기초
FileReader 와 FileWriter 는 char 배열이나 String 형태의 문자를 읽거나 썼다.
FileInputStream, FileOutputStream 는 바이트 형식의 데이터를 읽고 쓴다.
1) 바이트 형식 :
데이터의 크기의 단위, 자바의 자료형 byte 등등
바이트란 : 0 ~ 255 까지의 데이터이다.
1byte 크기가 8bit ( 1 bit 는 0과 1 의 값만 가질 수 있기 때문에 1 bit 로 표현이 가능한 범위는 두가지가 최대이다.
2bit 는 2 * 2 = 4 로 4가지를 표현 가능하다 ( 0, 1, 2, 3)
2 * 2 * 2 * 2 *2 * 2 * 2 * 2 이기 때문에 총 256 개의 표현이 가능하다.
이러한 바이트값들이 나열되어 있는 데이터 : 바이트 형식의 데이터.
컴퓨터는 바이트형식으로 데이터를 저장한다. 소켓 통신을 할 때도 : 바이트 단위의 데이터를 주고 받는다.
2. FileOutputStream 을 사용하여 바이트 형식의 데이터를 파일에 쓰기
~main {
byte[] data = { 77, 111, 113, 114, 39, 115, 32 } ;
//바이트 데이터는 우리가 무슨말 하는지 잘 모르니까 파일에 잘 정리해서 써보자 .
//바이트타입의 데이터가 들어있는 배열
try {
FileOutputStream file_output = new FileOutputStream("text");
//FileOutputStream 클래스의 객체를 생성.
// 내가 이해하기 쉬게 생각하자면 저 text 부분은 외부에 있는 파일중 하나일 수 있다.
그 파일로 객체 생성을 한것 ( 변수가 file_output )
file_output.write(data) ;
file_output.close();
: ** test라는 파일과 연결된 file_output 객체를 생성하여 write 메소드를 활용하여 data 를 file인 text에 쓰는것.
3. FileInputStream 을 사용하여 바이트 형식 데이터 읽기
main ~
byte[] data = new byte[64];
try {
FileInputStream file_input = new FileInputStream("test");
file_input.read(data);
FileInputStream 클래스에서는 read 라는 메소드를 제공하는데, 매개변수로 넘겨주는 버퍼에다가 데이터를 담아서 넘겨줍니다.
file_input.close();
} catch (FileNotFoundException e ) {
}catch(IOException 2 )
}
for(int i = 0 ; i < data.length ; ++i ) {
if(data[i] == 0 ) {
break; // 배열에서 데이터가 담기지 않은 부분은(64길이중에서) 0 값이 입력되기 때문에 if 문으로 데이터가 0 일때에는 for 문을 종료시킨다.
}
}
//
DataInputStream, DataOutputStream
숫자 데이터로 변환까지 해주어서 파일을 읽고 쓰는 클래스
DataInputStream 과 DataOutputStream 은 스스로 파일에 읽고 쓸 수는 없다.
그래서 전에 배웠던 FileInputStream 과 FileOutputStream 을 활용해야 한다.
~~
public static voud main ( String [] args ) {
FileOutputStrean f_stream = null ;
try {
f_stream = new FileOutputStream("test");
DataOutputStream d_stream = new DataOutputStream(f_stream);
}catch (FileNotFoundException e ) {
e.printStackTrace();
}
}
~~
DatainputStream 과 DataOutputStream 은 직접적으로 파일에 읽고 쓸 수는 없다. 따라서 FileInputStream 과 FileOutputStream 의 도움으로 파일에 읽고 쓸 수 있다.
예시 )
main ~ {
FileOutputStream f_stream = null;
try {
f_stream = new FileOutputStream('test");
DataOutputStream d_stream = new DataOutputStream(f_stream);
d_stream.writeInt(77);
f_stream.close();
d_stream.close();
} catch ( FileNotFoundException e ) {
}catch (IOExCEPTION e ) {
}
DataOutputStream 의 write 메소드
primitive 변수들을 바이트나 문자로 변형하지 않고도 위같은 메소드를 활용하여 파일에 저장 할 수 있다.
DataInputStream 을 사용하여 파일을 읽어보기
main {
FileInputStream f_stream = null;
try {
f_stream = new FileInputStream("test");
DataInputStream d_stream = new DataInputStream(f_stream);
System.out.println( d_stream.readInt());
f_steam.close();
d_stream.close();
} catch ( FileNotFoundException e ) {
}catch (IOException e ) {
}
read() 메소드들
ObjectInputStream , ObjectOutputStream
객체를 파일에 읽고 쓴다.
객체의 직렬화
객체를 파일에 쓴다는 말 : 객체를 스트림으로 만든다. : 객체의 직렬화
우리가 사용하는 모든 객체가 파일에 쓸 수 있는 것은 아니다
Serializable 인터페이스를구현한 클래스로 만든 객체여야 한다.
ex ) Date date = new Date(); 여기서 "date" 는 파일에 쓸 수 있다. 왜냐하면 Date 클래스가 Serializable 인터페이스를 구현했기 때문이다. (public class java.util Date implements java io.serializable )
ObjectOutputStream 사용해보기
~~~ main ~~ {
FileOutputStream f_stream = null;
Date date = new Date();
try {
f_stream = new FileOutputStream('test"); //ObjectOutputStream 은 스스로 File 에 접근할 수 없기 때문에 FileOutputStream 의 힘 빌려오기
ObjectOutputStream d_stream = new ObkectOutputStream(f_stream);
d_stream.writeObject(data); //byte 형식으로 써져서 이상한 내용들이 나옴.
//ObjectinputStream 으로 다시 읽으면 됨 ! ㅎㅎ
f_tream.close();
d_stream.close();
} catch (FileNotFoundException){
}catch(IOException )
ObjectInputStream 을 사용해 보기
~~main ~~ {
FilInputStream f_stream = null ;
Date date = null ;
try {
f_steam = new FileInputStream("test") ;
ObjectIntputStream d_stream = new ObjectInputStream (f_stream);
data = (Date)d_stream.readObject();
Systm.out.println(data.toString);
f_stream.close();
d_stream.close();
} catch ~~~~
BufferedInputStream , BufferedOutputStream
파일을 직접 읽거나 쓸 때마다 직접 하드(보조기억장치) 에 접근하기 때문에 성능저하우려
데이터를 읽어올 때 한번에 읽어 버퍼에 두거나, 데이터를 쓸 때 버퍼에 써 두고 한꺼번에 출력하는 방식인 버퍼를 사용해보자.
BufferedOutputStream 사용하기
얘도 스스로 파일에 접근하지 못하기 때문에 FileOutputStream 을 사용해야 한다.
자기의 버퍼에 데이터를 쌓아 두었다가 버퍼가 다 차면 보조기억장치로 접근하여 파일을 쓴다.
예시 )
main ~~ {
FileOutputStream f_stream = null;
try {
f_stream = new FileOutputStream("text");
byte receive[] = 'M', 'o' , 'r' ,'w' }
BufferedOutputStream b_out_stream = new BufferedOutputStream (f_stream, 1024);
b_out_stream.write(receive);
b_out_stream.close();
f_stream.close();
} catch ~~~~~
//임시로 저장할 버퍼의 크기를 마음대로 조절이 가능하다.
1024 크기로 마음대로 버퍼의 크기를 정할 수 있다. 즉 파일에 데이터를 쓰기 위해서넌 1024가 모여야 보조기억장치에 접근하여 쓰게 된다.
BufferedReader, BufferedWriter
BufferedInputStream , BufferedOutputStream 은 바이트 단위로 읽고 쓰고,
BufferedReader, BufferedWriter 는 문자로 읽고 쓴다.
BufferedWriter 사용하기
직접 파일에 접근할 수 없으니까 FileWriter 를 사용하여 객체를 생성 해야 한다.
main ~~ {
FileWriter f_writer = null;
try {
f_writer = new FileWriter("test");
BufferedWriter b_writer = new BufferedWriter(f_writer, 1024 ) ;
b_writer.write("Sujeong");
b_writer.close();
f_writer.close();
} catch ~~
BufferedWriter 클래스의 write 메소드들
BufferedReader 사용하기
main ~~ {
FileReader f_reader = null;
try {
f_reader = new FileReader("test");
char[[] str = new char[516];
BufferedReade b_reader = new BufferedReader(f_reader, 1024) ;
b_reader.read(str);
System.out.pritnln(String.valueOf(str) ;
b_reader.close();
f_reader.close();
}catch ~~~
BufferedReader 클래스의 read 메소드
ReadLine 메소드 ( FileReader 에서는 볼 수 없었던 메소드다 )
한 라인씩 읽어오는 메소드이다.
try 부분만 보면
FileReader f_reader = null ;
try {
f_reader = new FileReader("test");
BufferedReader b_reader = new BufferedReader(f_reader , 1024 ) ;
System.out.println("첫번째줄 : " + b_reader.readLine()) ;
System.out.println("두번째줄 : " + b_reader.readLine()) ;
System.out.println("세번째줄 : " + b_reader.readLine()) ;
b_reader.close();
f_reader.close();
} catch ~~~
댓글
댓글 쓰기