ABOUT ME

Today
Yesterday
Total
  • [JAVA] 바이트 스트림/버퍼스트림/File 클래스/바이트스트림과버퍼스트림 속도차이를 보여주는 예제/파일 복사 예제
    Languages/Java 2021. 4. 23. 18:55
    반응형

     

     

     

    바이트 스트림

     

    바이트 스트림

     

    바이트 단위의 바이너리 값을 읽고 쓰는 스트림

    동영상 파일, 이미지, 실행파일등을 처리할 때 유용

    바이트 스트림 클래스

    InputStream/OutputStream

     추상 클래스

     바이트 스트림을 다루는 모든 클래스의 슈퍼 클래스

    FileInputStream/FileOutputStream

     파일로부터 바이트 단위로 일거나 저장하는 클래스

     바이너리 파일의 입출력 용도

    DataInputStream/DataOutoutStream

     자바의 기본 데이터 타입의 값(변수)을 바이너리 값 그대로 입출력

     문자열도 바이너리 형태로 입출력

     

     

     

     

    클래스 InputStream과 OutputStream

     

    바이트 중심의 입출력을 담당하는 클래스

     

     

     

     

    InputStream

     

    파일로부터 내용을 바이트 기반으로 입력하기 위한 스트림

     

    생성자 

     인자 유형이 각각 String,File,FileDescriptor

     

    인자의 유형이 String과 File 인 경우

     지정된 인자의 파일이 존재하지 않는 경우에는 FileNotFoundExcetion을 발생

     처리를 위한 try - catch 문을 이용

     

     

    fileInputStream 과 fileOutputStream예제

    파일 복사 예제

     

    fileReader 소스와 매우 유사하다.

     

    package project4;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    public class CopyFileByte {
    
    	public static void main(String[] args) {
    		String input = "c:\\temp\\hello.jpg";
    		String output = "c:\\temp\\hellocopy.jpg";
    		
    		try {
    			FileInputStream fin = new FileInputStream(input);
    			FileOutputStream fout = new FileOutputStream(output);
    
    			int ch;
    			while((ch = fin.read()) != -1) {
    				fout.write(ch);			
    			}
    			System.out.println("작업완료 했습니다.");
    			fin.close();
    			fout.close();			
    		}catch (Exception e) {
    			e.printStackTrace();
    			System.out.println("오류발생");		
    		}
    	}
    }
    

     

     

     

    버퍼 입출력 스트림과 버퍼 입출력의 특징

     

    버퍼 스트림

     

    버퍼를 가진 스트림

    입출력 데이터를 일시적으로 저장하는 버퍼를 이용하여 입출력 효율 개선

     

    버퍼 입출력의 목적 

     입출력 시 운영체제의 API 호출 횟수를 줄여 입출력 성능 개선

     

     

     

    버퍼스트림의 종류

     

    바이트 버퍼 스트림

    바이트 단위의 바이너리 데이처를 처리하는 버퍼 스트림

    문자 버퍼 스트림

    유니코드의 문자데이터만 처리하는 버퍼 스트림

     

    BufferStreamEx

     

    버퍼 스트림과 바이트 스트림의 속도 차이를 보여주는 예제

     

    package project4;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    public class BufferStreamEx {
    
    	public static void main(String[] args) {
    		String input = "c:\\temp\\hello.jpg";
    		String output = "c:\\temp\\hellocopy.jpg";
    		long start,end,duration;
    		//버퍼 사용 복사
    		start = System.nanoTime();
    		try {
    			FileInputStream     fin = new FileInputStream(input);
    			BufferedInputStream bin = new BufferedInputStream(fin);
    			FileOutputStream     fout = new FileOutputStream(output);
    			BufferedOutputStream bout = new BufferedOutputStream(fout);
    			int ch;
    			while((ch = bin.read()) != -1 ) {
    				bout.write(ch);
    			}
    			System.out.println("버퍼 작업이 완료되었습니다");
    			bin.close();
    			bout.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    			System.out.println("버퍼사용 예외 방생");
    		}
    		end = System.nanoTime();
    		duration = end - start;
    		System.out.println("버퍼를 활용한 경우 : "+ duration);
    		
    		//일반파일 복사
    		start = System.nanoTime();
    		try {
    			FileInputStream fin = new FileInputStream(input);
    			FileOutputStream fout = new FileOutputStream(output);
    
    			int ch;
    			while((ch = fin.read()) != -1) {
    				fout.write(ch);			
    			}
    			System.out.println("작업완료 했습니다.");
    			fin.close();
    			fout.close();			
    		}catch (Exception e) {
    			e.printStackTrace();
    			System.out.println("오류발생");		
    		}
    		end = System.nanoTime();
    		duration = end - start;
    		System.out.println("파일만 사용한 경우 : "+ duration);
    	}
    }
    

     

     

     

     

     

     

     

    File 클래스

     

     

     

    파일의 경로명을 다루는 클래스

     java.io.File

    파일의 디렉터리 경로명의 추상적 표현

     

    파일 관리 기능

     파일 이름 변경,삭제,디렉터리 생성, 크기 등 파일 관리

     File 객체는 파일 읽고 쓰기 기능 없음

     

    파일과 폴더에 대한 여러 연산을 수행하기 위한 클래스

     

     

     

    File 클래스 사용 예

     

     

    파일 객체 생성

    File f = new File("c:\\windows\\system.ini");

     

     

    파일의 경로명 getName(),getPath(),getParent()

    getName()은 파일명만, hetPath()는 완전경로명을, getParent()는 부모 디렉터리를 문자열로 리턴한다.

    String filename = f.getName();//"system.ini"
    String path = f.getPath(); // "c:\\windows\\system.ini"
    String parent = f.getParent(); //"c:\\windows"

     

     

    파일인지 디렉터리인지 구분 isFile(), isDirectory()

     

    isFile()과 isDirectory()는 경로명이 파일인지 디렉터리인지에 따라

    true/false를 리턴한다. 

     

    if(f.isFile()) //파일인 경우
    	System.out.println(f.getPath() + "는 파일입니다.");
    else if(f.isDirectory()) // 디렉터리인 경우
    	System.out.println(f.getPath() + "는 디렉터리입니다.");

     

     

    서브 디렉터리 리스트 얻기

     

    File 객체가 디렉터리의 경로명을 가진 경우, 디렉터리의 모든 파일과 

    서브 디렉터리의 리스트를 얻을 수 있다.

     

    File f = new File("c:\\TEmp");
    File[] subfiles = f.listFiles();//c:\Temp 파일 및 서브 디렉터리 리스트 얻기
    
    for(int i=0;i<filenames.lengh;i++){
    	System.out.print(subfiles[i].getName());//파일명 출력
        System.out.println("\t파일크기: " + subfiles[i].length()); //크기 출력
    }
    반응형

    댓글

Designed by Tistory.