출처 : Java 의 정석 ppt http://www.javachobo.com
바이트기반 스트림 : InputStream , OutputStream
: 데이터를 바이트 단위로 주고 받는다.
입력 스트림 출력스트림 대상
FileInputStream FileOutputStream 파일
ByteArrayInputStream ByteArrayOutputStream 메모리
PipedInputStream PipedOutputStream 프로세스
AudioInputStream AudioOutputStream 오디오장치
public abstract class InpuStream{
abstract int read() //입력스트림으로부터 1byte 를 읽어서 반환한다. 읽을 수 없으면 -1 반환
* abstract 메소드라서 InputStream 의 자손들은 자신의 상황에 맞게
int read(byte[] b , int off, int len ) { //입력스트림으로부터 len 개의 byte 를 읽어서 byte 배열 b 의 off 위치부터 저장한다.
for( int i = off ; i <off+len ; i++ ) {
// read() 를 호출해서 데이터를 읽어서 배열을 채운다.
b[i] = (byte)read();
}
}
int read(byte[] b ) { //입력스트림으로 부터 byte 배열 b 의 크기만큼 데이터를 읽어서 배열 b 에 저장한다.
return read(b, 0 , b.length) ;
}
보조스트림
스트림의 기능을 향상시키거나 새로운 기능을 추가하기 위해 사용한다. 독립적으로 입출력 수행 불가능
1. 먼저 기반스트림을 생성한다.
FileInputStream fis = new FileInputStream("test.txt");
2. 기반스트림을 이용해서 보조스트림을 생성한다.
bufferedInputStream bis = new BufferedInputStream(fis) ;
3. 보조스트림인 BufferedInputStream 으로부터 데이터를 읽는다.
bis.read() ;
****
입력 출력 설명
FilterInputStream FilterOutputStream 필터를 이용한 입출력 처리
BufferedInputStream BufferedOutputStream 버퍼를 이용한 입출력 성능 향상
DataInputStream DataOutputStream int, float 와 같은 기본형 단위(primitive type) 로 데이터를 처리하는 기능
SequenceInputStream SequenceOutputStream 두개의 스트림을 하나로 연결
LineNumberInputStream 없음 읽어온 데이터의 라인 번호를 카운트 (JDK1.1부터 LineNumberReader )
(LineNumberReader )
ObjectInputStream ObjectOutputStream 데이터를 객체단위로 읽고 쓰는데사용
주로 파일을 이용하여 객체 직렬화와
관계있음
없음 PrintStream 버퍼를 이용하며, 추가적인 print관련
기능
PushbackInputStream 없음 버퍼를 이용해서 읽어온 데이터를 다시 되돌리는 기능 (unread)
문자 기반 스트림 - Reader , Writer
입출력 단위가 문자(char, 2 byte ) 인 스트림 . 문자기반 스트림의 최고 조상
출처 : 자바의 정석 ppt
ByteArrayInputStream 과 ByteArrayOutputStream
- 바이트배열(byte[] ) 에 데이터를 입출력하는 바이트기반 스트림
class IOEx1 {
public static void main (String [] args ) {
byte[] inSrc = {0,1,2,3,4,5,6,7,8,9 } ;
byte[] outSrc = null ;
ByteArrayInputStream input = null ;
ByteArrayOutputStream output = null ;
input = new ByteArrayInputStream(inSrc) ; 읽어오려고
output = new ByteAttayOutputStream(); 출력해주려고
int data = 0 ;
while( (data = input.read() ) != -1 ) {
output.write(data) ; // void write(int b )
}
outSrc = output.toByteArray(); // 스트림의 내용을 byte 배열로 반환
System.out.println("Input source : " + Arrays.toString(inSrc));
System.out.println("output source : " + Arrays.toString(outSrc));
또 다른 예제 위에것 변형 )
class IOEx3 {
public static void main(String[] args ) {
byte[] inSrc = {0,1,2,3,4,5,6,7,8,9 } ;
byte[] outSrc = null;
byte[] temp = new byte[4]; //위에 꺼랑 배열 길이가 다르다.
ByteArrayInputStream input = null ;
ByteArrayOutputStream output = null;
input = new ByteArrayInputStream(inSrc);
output = new ByteArrayOutputStream();
try{
while ( input.available () > 0 ) {
input.read(temp); int len = input.read(temp);
output.write(temp); output.write(temp, 0, len ) ;
}
} catch(IOException e ) {}
outSrc = output.toByteArray();
System.out.println("Input Source : " + Arrays.toString(inSrc)) ;
System.out.println("temp : " + Arrays.toString(temp)) ;
System.out.println("temp : " + Arrays.toString(outSrc)) ;
실행결과 :
FileInputStream 과 FileOutputStream
- 파일(file) 에 데이터를 입출력하는 바이트기반 스트림
FileInputStream(String name) 지정된 파일이름(name) 을 가진 실제 파일과 연결된 FileInput Stream) 을 생성한다.
FileInputStream(File file) 파일의 이름이 String 이 아닌 File 인스턴스로 지정해주어야 하는 점을 제외하고 FileInputStream(String name) 와 같다.
FileOutputStream(String name) 지정된 파일이름을 가진 실제 파일과 연결된 FileOutputStream 을 생성한다.
FileOutputStream(String name, boolean append) 지정된 파일이름(name) 을 가진 실제 파일과 연결된 File OutputStream 을 생성한다. 두번째 인자인 append를 true 로 하면 , 출력시 기존의 파일내용의 마지막에 덧붙인다. false 면 기존의 파일내용을 덮어쓰게 된다.
FileOutputStream(File file) 파일의 이름을 String 이 아닌 File 인스턴스로 지정해주어야 하는 점을 제외하고 FileOutputStream(String name ) 과 같다
class FileCopy {
public static void main(String args[] ) {
try {
FileInputStream fis = new FileInputStream(args[0]);
FileOutputStream fos = new FileOutputStream(args[1]) ;
int data = 0 ;
while( (data = fis.read() ) != -1 ) {
fos.write(data); // void write(int b )
}
fis.close();
fos.close();
}catch (IOException e ) {
e.printStackTrace() ;
}
}
}
표준입출력과 File
표준입출력 - System.in, System.out, System.err
콘솔을 통한 데이터의 입출력 : 표준 입출력
RandomAccessFile
-하나의 스트림으로 파일에 입력과 출력을 모두 수행할 수 있다.
- 다른 스트림과는 달리 Object 의 자손이다.
직렬화
객체를 '연속적인 데이터'로 변환하는것. 반대과정은 '역질렬화'라고 한다.
객체의 인스턴스변수들의 값을 일렬로 나열하는 것
객체를 저장하기 위해서는 객체를 직렬화해야한다.
객체를 저장한다는 것은 객체의 모든 인스턴스변수의 값을 저장하는 것
ObjectInputStream, ObjectOutputStream
객체를 직렬화하여 입출력할 수 있게 해주는 보조 스트림
ObjectInputStream(InputStream in )
ObjectOutputStream(OutputStream out )
객체를 파일에 저장하는 방법
FileOutputStream fos = new FileOutputStream("objectfile.ser" ) ;
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(new UserInfo());
파일에 저장된 객체를 다시 읽어오는 방법
FileinputStream fis = new FileInputStream(:objectfile.ser");
ObjectInputStream in = new ObjectInputStream(fis);
UserInfo info = (UserrInfo)in.readObject();
File : 생성자와 경로 3가지가 있다.
1) File (String fileNam) -> 파일이름과 경로가 모두 들어있다.
2) File (String pathName, String fileName)
3) File (File pathName , String fileName)
-static String pathSeparator
static Char pathSeparator
: 둘은 같은 것
- c:\windoews\TEMP\work14247.tmp : 임시파일 저장되는 경로
FileTest01
----------------------------------------------------------------------------------------------
package ar.or.ddit.basic;
import java.io.File;
public class FileTest01 {
public static void main(String[] args) {
// File 객체 만들기 연습
// 1. new File(String 파일 또는 경로 ) ;
// ==> 디렉토리와 디렉토리 사이 또는 디렉토리와 파일명 사이의 구분문자는
// 역슬레쉬 ( '\' )를 사용하거나 슬레쉬 ( '/') 를 사용할 수 있다.
File file1 = new File("D:/D_Other/text.txt"); //구분문자로 '/' 사용한 경우
//File file1 = new File("D:\\D_Other\\text.txt"); //구분문자로 '\' 사용한 경우
System.out.println("파일명 : " + file1.getName());
System.out.println("디렉토리일까? : " + file1.isDirectory());
System.out.println("파일일까? : " + file1.isFile() );
System.out.println();
File file2 = new File("D:/D_Other"); //경로까지만 나왔음
System.out.println("파일명 : " + file2.getName());
System.out.println("디렉토리일까? : " + file2.isDirectory());
System.out.println("파일일까? : " + file2.isFile() );
System.out.println();
//2. new File(File parent , String child )
// ==> 'parent' 디렉토리 안에있는 'child' 파일을 나타낸다.
File file3 = new File(file2 , "text.txt");
// File file1 = new File("D:/D_Other/text.txt"); 과
//File file2 = new File("D:/D_Other"); 를 분리해서 쓴것 .
System.out.println("파일명 : " + file3.getName());
System.out.println("디렉토리일까? : " + file3.isDirectory());
System.out.println("파일일까? : " + file3.isFile() );
System.out.println();
// 3. new File ( String parent, String child )
// ==> 'parent ' 디렉토리 안에 있는 'child' 파일을 나타낸다.
File file4 = new File("d:/D_other", "text.txt");
System.out.println("파일명 : " + file4.getName());
System.out.println("디렉토리일까? : " + file4.isDirectory());
System.out.println("파일일까? : " + file4.isFile() );
System.out.println();
// 디렉토리 ( 폴더 )만들기
/*
*
* -mkdir() ==> File 객체의 경로 중 마지막 위치의 디렉토리를 생성한다.
* ==> 반환값 : 만들기 성공 (true) 만들기 실패 (false)
* ==> 중간 부분의 경로가 모두 만들어져 있어야 마지막 위치의 폴더를 만들 수 있다.
* -mkdirs() ==> 중간 부분의 경로가 없으면 중간 부분의 경로도 같이 만들어 준다.
*
*
*/
File file5 = new File("D:/D_Other/연습용");
System.out.println("파일명 : " + file5.getName());
System.out.println("디렉토리일까? : " + file5.isDirectory());
System.out.println("파일일까? : " + file5.isFile() );
System.out.println();
System.out.println(file5.getName() + "의 존재여부 : " + file5.exists());
if(file5.mkdir()) {
System.out.println(file5.getName() + "디렉토리 만들기 성공 ~");
}else { //폴더가 있는데 똑같은 이름으로 만들려고 하면 실패가 뜬다.
System.out.println(file5.getName() + "디렉토리 만들기 실패 !!");
}
System.out.println();
File file6 = new File("D:/D_Other/text/java/src");
if(file6.mkdirs()) { //mkdir 은 맨마지막 src 를 만드는데 java (부모폴더에) 만든다. 만약 부모폴더 java 가 없으면 만들기 실패
//text 폴더도 없음.. 그럼 디렉토리만들기가 실패하니까 mkdirs() 를 써줘서 다만들게 ..
System.out.println(file6.getName() + "디렉토리 만들기 성공 ");
}else {
System.out.println(file6.getName() + "디렉토리 만들기 실패");
}
}
}
FileTest02
package ar.or.ddit.basic;
import java.io.File;
public class FileTest02 {
public static void main(String[] args) {
File f1 = new File("d:/D_Other/text.txt");
System.out.println(f1.getName() + "의 크기 : " + f1.length() + "bytes");
System.out.println("Path : " + f1.getPath());
System.out.println("AbsolutePath : " + f1.getAbsolutePath());
System.out.println();
File f2 = new File(".");
System.out.println("Path : " + f2.getPath());
System.out.println("AbsolutePath : " + f2.getAbsolutePath());
System.out.println();
if(f1.isFile()) {
System.out.println(f1.getName() + "은 파일입니다.");
}else if(f1.isDirectory()) {
System.out.println(f1.getName() + "은 디렉토리(폴더)입니다.");
}else {
System.out.println(f1.getName() + "은 뭘까???");
}
System.out.println();
if(f2.isFile()) {
System.out.println(f2.getName() + "은 파일입니다.");
}else if(f2.isDirectory()) {
System.out.println(f2.getName() + "은 디렉토리(폴더)입니다.");
}else {
System.out.println(f2.getName() + "은 뭘까???");
}
System.out.println();
File f3 = new File("d:/D_Other/sample.exe"); // 현재 존재하지 않는 파일을 지정했을 때
if(f3.isFile()) {
System.out.println(f3.getName() + "은 파일입니다.");
}else if(f3.isDirectory()) {
System.out.println(f3.getName() + "은 디렉토리(폴더)입니다.");
}else {
System.out.println(f3.getName() + "은 뭘까???");
}
}
}
-----------------------------------------------------------------------------------------------
FileTest3
package ar.or.ddit.basic;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileTest03 {
public static void main(String[] args) {
FileTest03 test = new FileTest03();
File viewFile = new File("d:/공유폴더"); // 보고싶을 디렉토리 설정
test.displayFileList(viewFile);
}
// 디렉토리(폴더)를 매개값으로 받아서 해당 디렉토리(폴더)에 있는
// 모든 파일과 디렉토리(폴더) 목록을 출력하는 메서드
public void displayFileList(File dir) {
if(!dir.isDirectory()) {
System.out.println("디렉토리(폴더)만 가능합니다.");
return;
}
System.out.println("[" + dir.getAbsolutePath() + "] 디렉토리 내용");
System.out.println();
// 해당 디렉토리 안에 있는 모든 파일과 디렉토리 목록을 구해온다.
File[] files = dir.listFiles();
//String[] filestrs = dir.list();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd a hh:mm");
// 가져온 파일과 디렉토리 목록 개수만큼 반복처리하기
for(int i=0; i<files.length; i++) {
String fileName = files[i].getName();
String attr = ""; // 파일의 속성 (읽기, 쓰기, 히든, 디렉토리를 구분)
String size = ""; // 파일의 크기
if(files[i].isDirectory()) {
attr = "<DIR>";
}else {
size = files[i].length() + "";
attr = files[i].canRead() ? "R" : "";
attr += files[i].canWrite() ? "W" : "";
attr += files[i].isHidden() ? "H" : "";
}
System.out.printf("%s %5s %12s %s\n",
df.format(new Date(files[i].lastModified())),
attr, size, fileName );
}
}
}
댓글
댓글 쓰기