ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • IO,NIO(New I/O), Enum(열거타입)
    JAVA 2021. 7. 23. 16:16

    입출력(IO)

    경로를 못찾을 수도 있어 예외를 던져놓음, 예외처리를 해줘야함

    1. 바이트 기반

    Input: InputStream

    InputStream은 바이트기반 입력스트림의 최상위 추상클래스이다.(마치 Collection과 List, Set의 컬렉션프레임워크 관계처럼..)

    BufferdInputStream, DataInputStream은 모두 InputStream을 상속하고 있다.

    (입력: 있는 파일 읽어와 저장, 자바에 입력되는??)

    InputStream의 주요 메서드

    1. read(): 입력스트림으로부터 1byte씩 읽어서 4byte int타입으로 리턴

    2. read(byte[] byte): 입력스트림으로부터 주어진 byte배열의 길이만큼 데이터를 읽고 읽은 byte수만큼 리턴

    3. read(byte[] b, int off, int len): 입력스트림으로부터 len바이트수 만큼 읽어서 매개값으로 주어진 배열 b[off]로 부터 len까지 리턴

    4. close(): InputStream을 더 이상 사용하지 않을 경우 InputStream에서 사용자원을 해제

    Output: OutputStream

    OutputStream은 바이트기반 출력스트림의 최상위 추상클래스이다. 모든 바이트기반 출력 스트림

    (FileOuputStream, PrintOutputStream,DataOutputStream)은 모두 OutputStream을 상속한다.

    (출력: 파일을 만들어 저장, 자바에서 출력하는??)

    OutputStream의 주요 메서드

    1. write(int b): 1바이트씩 출력

    2. write(byte[] b): 매개값으로 주어진 바이트배열 바이트씩 출력

    3. write(byte[] b, int off, int len): b[off] 부터 len까지의 바이트를 출력

    4. flush(): 버퍼에 남아있는 바이트 전부를 출력

    ... 출력스트림은 내부에 작은 buffer가 있어서 데이터가 출력되기 전에 버퍼에 저장하고 있다가 순서대로 출력이 되는데

    flush() 메서드는 버퍼에 남아있는 모든 데이터를 출력시키고 버퍼를 비운다.

    5. close(): 사용된 자원을 반납하고 출력 스트림을 닫는다.

    2. 문자 기반

    Input: Reader

    Reader

    Reader는 문자기반 입력스트림의 최상위 클래스이다. 모든 문자기반 입력스트림

    (FileReader, BufferReader, InputStreamReader)은 모두 Reader클래스를 상속한다.

    Reader클래스의 주요메서드

    1. read(): 입력스트림으로부터 한개의 문자를 읽고 리턴

    2. read(char[] cbuf): 읽은 문자를 문자배열 cbuf에 저장하고 실제로 읽은 문자를 리턴

    3. read(char[] buf, int off, int len): len개의 문자를 읽고 char[off]부터

    len개까지의 문자를 저장하고 실제 읽은 문자수 len을 리턴

    4. close()

    Output: Writer

    바이트 기반 Output과 동일한 논리

    3. 파일입출력

    File 클래스

    IO패키지에서 제공하는 File클래스는 파일크기,속성,이름등의 정보를 읽는 기능과

    파일생성, 삭제관련기능등을 제공한다. 또한 디렉토리를 생성하고 디렉토리내에 있는 파일의 리스트를 읽는 기능도 제공한다.

    하지만, 파일의 데이터를 읽고 쓰는 기능은 지원하지 않는다. 파일에 데이터를 입출력하려고 할 경우에는 입출력스트림을 사용해야 한다.

    디렉토리구분자는 윈도우에서는 '\' or '/' 리눅스에서는 '/'을 사용한다. 만약에 '/'을 사용할 경우에는 이스케이프문자('\\')로 사용해야 한다.

    그래서 / 하나로 그냥 사용하는게 편함.

    File관련 주요메서드

    1.createNewFile(): 새로운 파일을 생성

    2.mkdir(): directory를 생성

    3.mkdirs(): 경로상에 없는 모든 directory를 생성

    4.delete(): 파일 or directory를 삭제

    파일 또는 directory가 존재할 경우에 관련된 메서드

    1. canExecute(): 실행가능 파일여부인지

    2. canRead(): 읽을 수 있는 파일인지 여부

    3. canWrite(): 수정 및 저장할 수 있는 파일 여부

    4. getName(): 파일이름을 리턴

    5. getParent(): 부모디렉토리를 리턴

    6. getParentFile(): 부모디렉토리를 File객체로 생성후 리턴

    7. getPath(): 전체경로를 리턴

    8. isDirectory(): 디렉토리여부를 리턴

    9. isFile(): 파일여부를 리턴

    10. isHidden(): 숨긴파일인지를 리턴

    11. lastModified(): 마지막 수정일시를 리턴

    12. length(): 파일크기를 리턴

    13. list(): 디렉토리에 포함된 파일 및 서브디렉토리 목록전부를 String배열로 리턴

    14. list(FilenameFilter filter): list()와 동일, 차이점은 filter조건에 맞는 것만 리턴

    15. listFiles(): 디렉토리에 포함된 파일 및 서브디렉토리 목록전부를 File배열로 리턴

    16. listFiles(FilenameFilter filter): listFiles()와 동일, 차이점은 filter조건에 맞는 것만 리턴

    FileInputStream 클래스

    이 클래스는 파일로부터 바이트단위로 읽어 올 때 사용하는 바이트기반 입력스트림이다.

    바이트단위로 읽기 때문에 그림, 오디오, 비디오, 텍스트파일등 모든 종류의 파일을 읽을 수 있다.

    FileInputStream을 생성하는 2가지 방법

    1. 문자열로 된 파일경로를 가지고 생성

    FileInputStream fis = new FileInputStream("c:/temt/img.gif")

    2. File 객체로 이미 생성이 되어 있을 경우

    File file = new File("c:/temp/img.gif")

    FileInputStream fis = new File(file);

    FileOutputStream 클래스

    있는 파일을 복사(내가 파일 다운로드 받을 때 이런 과정이다.)

    FileReader 클래스

    파일들 가져와 읽기

    FileWriter 클래스

    파일을 만들어 내보내기


    NewIO(NIO)

    IO를 더 보충해서 나옴.

    NIO(New Input Output)

    Java4부터 새로운 입출력이라는 뜻에서 java.nio패키지가 포함되었는데 java7로 버전업이 되면서

    비동기채널등의 network지원을 대폭강화한 NIO.2API가 추가 되었다.

    NIO.2는 java.nio2 패키지로 통합되지 않고 java.nio로 통합되었다.

    1. IO와 NIO의 차이점

    1) 입출력방식: IO는 stream방식(단방향)이지만 NIO 채널방식(양방향)이다.

    2) 버퍼방식 : IO는 Non Buffer, NIO는 Buffer방식으로 처리

    3) 비동기방식: IO는 동기방식만, NIO는 동기/비동기방식 모두 지원

    4) 블럭킹 : IO는 블럭킹방식, NIO는 블러킹/넌블러킹방식 모두 지원

    2. 파일과 디렉토리

    IO는 파일의 속성정보를 읽기 위해 File클래스만 제공하지만 NIO는 좀더 다양한 파일의 속성정보를 제공하는

    클래스와 인터페이스를 java.nio.file, java.nio.file.attribute패키지를 제공한다.

    1) 경로정의(Path)

    2) 파일시스템정보(FIleSystem)

    3) 파일속성 읽기 및 파일/디렉토리 생성,삭제

    4) 워치서비스(WatchService)

    3. 버퍼

    NIO에서는 데이터를 입출력하려면 항상 버퍼를 사용해야 한다. Buffer의 종류는 어떤 메모리를 사용하느냐에 따라

    Direct와 NonDirect로 구분된다.

    NonDirect버퍼는 JVM에서 관리하는 힙메모리공간을 이용하는 buffer이고 Direct버퍼는 운영체제가 관리하는

    메모리공간을 이용하는 버퍼이다.

    두 버퍼의 차이점은 버퍼생성시간이 NonDirect버퍼가 빠르고 버퍼의 크기는 NonDirect버퍼가 작다.

    (대용량의 데이터를 처리할 때는 Direct버퍼를 이용하는 것이 좋다.) 입출력성능은 NonDirect의 성능이 낮다.

    (운영체제 안에서 JVM이 설치된 것이니 성능이 낮은건 당연)

    파일채널

    java.nio.channels.FileChannel 을 이용하면 파일을 읽기와 쓰기가 가능하다. FileChannel은 동기화처리가

    되어 있기 때문에 멀티쓰레드 환경에서 사용해도 안전하다.

    1. FileChannel 생성과 닫기

    FileChannel.open() 메서드는 정적메서드로서 이 메서드를 호출하거나 IO의

    FileInputStream, FileOutputStream의 getChannel()메서드를 호출해서 얻을 수 있다.

    사용법은 FileChannel.open(Path path, OpenOption ... options)으로 열기를 하는데 OpenOption은

    READ, WRITE, CREATE, CREATE_NEW, APPEND, DELETE_ON_CLOSE, TRUCATE_EXISTING등이 있다.

    그리고 파일을 더이상 사용하지 않을 경우에는 close() 메서드를 호출해서 닫아야 한다.

    2. 파일읽기와 쓰기

    파일에 바디트를 쓰려면 FileChannel.write()메서드를 호출하면 된다. 매개값으로 ByteBuffer 객체를

    전달하는데 파일에 쓰여지는 바이트(데이터)는 ByteBuffer의 position부터 limit까지이다.

    position이 0이고 limit가 capacity(버퍼의)와 동일하다면 버퍼의 모든 바이트가 파일에 쓰여진다.

    파일로부터 바이트를 읽기 위해서는 read()메서드를 호출하면 된다. 매개값으로 ByteBuffer가 주어지고

    position부터 읽게된다. read()의 메서드의 리턴값은 파일에서 읽혀진 바이트이다.

    한번에 읽을 수 있는 최대 바이트수는 capacity까지이기 때문에 최대값은 capacity가 되고 더이상 읽을

    바이트가 없다면 -1로 리턴한다.

    3. 파일복사

    파일복사를 구현하기 위해서는 ByteBuffer를 중간에 두고 읽기용, 쓰기용 FileChannel을 번갈아 수행.


    자바기초1

    1. 데이터타입분류

    1) 기본(premitive)타입: 정수,실수,논리리터럴을 저장하는 타입

    2) 참조(reference)타입: 객체의 번지를 참조하는 타입, 배열, 열거, 클래스, 인터페이스

    기본타입과 참조타입의 차이점은 기본 타입은 실제값을 변수에 저장, 참조타입은 객체의

    번지를 값으로 갖는다. 번지를 통해서 객체를 참조한다는 의미로 참조타입이라고 한다.

    2. 메모리사용영역

    1) Method영역: 코드에서 사용되는 클래스(~.class)파일들을 클래스로더로 읽어 클래스별로

    상수,필드,메서드 생성자등을 구분해서 저장된다. 이 영역은 모든 쓰레드(프로그램)이 공유하는 영역이다.

    2) Heap영역: 힙영역은 객체와 배열이 생성되는 영역이다. 힙영역에 생성된 객체와 배열은 스택영역의 변수나

    다른 객체의 필드에서 참조한다. 참조하는 변수나 필드가 없다면 의미가 없는 객체가 되기 때문에

    이것을 쓰레기로 취급하고 JVM은 쓰레기수집기(Garbage Collector)를 실행시켜서 객체를 힙영역에서

    자동으로 해제한다. 그렇기 때문에 개발자는 제거를 위한 별도의 코드를 작성할 필요가 없다.

    3) Stack영역: JVM의 스택영역은 각 쓰레드(프로그램)마다 하나씩 존재하며 쓰레드(프로그램)이 실행될 때마다 할당이 된다.

    자바기초2

    1. 배열이란?

    변수는 한개의 값만 저장할 수 있다. 하지만 저장할 데이터의 수가 많아지면 그 수만큼의 변수가 필요하게 된다.

    이러한 방법은 매우 비효율적이고 지루한 코딩이 된다. 동일타입의 많은 양의 데이터를 다룰 경우 좀 더 효율적인

    방법으로 데이터를 저장할 필요가 있는데 이것이 배열이다.

    배열은 동일타입의 데이터를 연속된 공간에 나열시키고 각 데이터에 index를 부여해 놓은 자료구조이다.

    2. 배열선언방법

    배열의 선언방법은 2가지가 있다. "타입[] 변수" or "타입 변수[]"로 선언하는데 대괄호[]는 배열변수를 선언하는

    기호가 된다. 대괄호는 데이터타입 뒤에 붙을수도 있고 변수뒤에 붙을 수도 있다.

    배열은 참조변수로서 객체이기 때문에 힙영역에 생성되고 배열변수는 힙영역의 배열객체를 참조한게 된다.

    참조할 배열객체가 없다면 배열변수는 null값으로 초기화할 수 있다.

    3. 배열생성방법

    1) 값목록으로 생성하는 방법

    String[] name = {"홍길동", "홍길순"}; 와 같이 중괄호{}는 주어진 값들을 항목으로 가지는 객체를 생성한다.

    2) new연산자로 생성하는 방법

    값목록은 없지만 향후에 값을 저장할 배열을 미리 만들고자 할 경우에 new연산자로 배열객체를 생성할 수 있다.

    int[] name = new int[5];

    new연산자로 생성된 배열은 기본값으로 null이 저장되며 배열을 생성한 후에 값을 저장하려면

    arr[0] = 10 과 같이 대입연산자를 사용하면 된다.


    열거타입

    데이터중에는 몇가지로 한정된 값만 갖는 경우가 많다.

    예를 들어 요일에 대한 월~일이라는 일곱개의 값만 가지고 있고 계절에 대한

    데이터는 봄,여름,가을,겨울이라는 네개의 값만 가지는 것 처럼

    이와 같이 한정된 값만 갖는 데이터를 열거타입(Enumeration Type) 이라고 한다.

    열거타입은 몇개의 열거상수중에수 하나의 상수를 저장하는 데이터 타입이다.

    열거타입을 선언하기 위해서는 먼저 열거타입의 이름을 정하고 열거 타입이름으로 소스파일(~.java)을 생성해야 한다.(Enum파일로)

    열거타입이름은 관례적으로 첫문자를 대문자로, 나머지는 소문자로 한다. 만약, 여러단어로 구성되어 있다면 Camel Case를 준수한다.

    (클래스 이름 조건과 동일하다.)

    Week라는 열거타입을 선언했다면 열거타입을 사용할 수 있다.

    열거타입도 하나의 데이터타입이므로 변수를 선언하고 사용해야 한다.(열거도 객체이다)

    열거타입변수를 선언했다면 열거상수를 저장할 수 있다. 열거상수는 단독으로

    사용할 수 없고 반드시 "열거타입.열거상수"로 사용해야한다.

    열거상수는 static fianl로 자동 선언되있다. 변수를 만들어 변수명으로 접근해도 되고

    그냥 열거타입이름으로 접근해도 됨(클래스멤버를 클래스.필드 하듯이)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public enum Week {
     
        MONDAY,
        THESDAY,
        WEDENSDAY,
        THURSDAY,
        FRIDAY,
        SATURDAY,
        SUNDAY,
        월요일,
        화요일,
        수요일,
        목요일,
        금요일,
        토요일,
        일요일
    }
    cs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
            Week today = null;
            System.out.println(today.WEDENSDAY);
            System.out.println(today.수요일);
     
            // 실습: 현재요일을 확인하는 로직을 작성
            // Calendar, switch 문을 이용해서 오늘의 요일 출력
     
            Calendar now = Calendar.getInstance();
            int calendar = now.get(Calendar.DAY_OF_WEEK);
     
            switch (calendar) {
            case 1:
                today = Week.일요일;
                break;
            case 2:
                today = Week.월요일;
                break;
            case 3:
                today = Week.화요일;
                break;
            case 4:
                today = Week.수요일;
                break;
            case 5:
                today = Week.목요일;
                break;
            case 6:
                today = Week.금요일;
                break;
            default:
                today = Week.토요일;
            }
     
            System.out.println("오늘의 요일은 " + today);
    cs

     


    InputStream: 바이트 기반

    ReadMain1

    File로 생성 - 이름 뒤에 txt로 텍스트 파일 완성

    Java
    대한민국
    IO Network
    JavaFX
    String
    NIO
    JDBC

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
        public static void main(String[] args) throws Exception {
     
            InputStream is = new FileInputStream("src/com/lec206/ex01_input/news.txt");//파일 주소를 받아서 new File(String) 생성해서 리턴
            
            int readByte;
            while(true) {
                readByte = is.read();    //1byte씩 읽기
                if(readByte == -1)break;
                System.out.println((char)readByte);//문자를 읽으니까, int로 하면 유니코드 숫자가 나온다. 그래서 char로 형변환
                //하지만 한글은 깨진다 - 한글은 3byte라서 지금은 1byte만 읽으니까.
            }
            is.close();
            
        }
    cs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
        public static void main(String[] args) throws Exception {
     
            InputStream is = new FileInputStream("src/com/lec206/ex01_input/news.txt");//파일 주소를 받아서 new File(String) 생성해서 리턴
            
            int readByte;
            String data = "";
            
            byte[] readBytes = new byte[3];
            while(true) {
                readByte = is.read(readBytes);    //3byte씩 읽기
                if(readByte == -1break;
                data += new String(readBytes,0,readByte);
            }
            System.out.println(data);
            is.close();
            
        }
    cs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
        public static void main(String[] args) throws Exception {
     
            InputStream is = new FileInputStream("src/com/lec206/ex01_input/news.txt");//파일 주소를 받아서 new File(String) 생성해서 리턴
            
            int readByteNo;
            byte[] readBytes = new byte[8];
     
            readByteNo = is.read(readBytes,2,3);
            for(int i =0; i<readBytes.length;i++) {
                System.out.println((char)readBytes[i]);
            }
            is.close();
            
        }
    cs

    OutputStream: 바이트 기반

    WriteMain

    refresh하면 txt파일 3개가 지정한 경로에 생성된다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
        public static void main(String[] args) throws Exception {
     
            OutputStream os = new FileOutputStream("src/com/lec206/ex02_output/sample1.txt");
            //나중에 input으로 읽을 수 있는 txt파일을 생성하는 것이다.
     
            // 1. write(byte[] b)
            byte[] data = "ABCDEF".getBytes();    
            for (int i = 0; i < data.length; i++) {
                os.write(data[i]);
            }
            os.flush();
            os.close();
     
            // 2. write()
            os = new FileOutputStream("src/com/lec206/ex02_output/sample2.txt");
            data ="1234567890".getBytes();
            os.write(data);
            os.flush();
            os.close();
            
            // 3. write(byte[] b, int off, int len)
            os = new FileOutputStream("src/com/lec206/ex02_output/sample3.txt");
            data ="aassdd한글".getBytes();    //영어 1byte, 한글 3byte씩 : 6개 영어 + 2개 한글 = 12byte
            os.write(data,0,12);
            os.flush();
            os.close();
     
        }
     
    cs

    Input: Reader: 문자 기반

    ReaderMain

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
        public static void main(String[] args) throws Exception {
     
            Reader reader = null;
     
            // 1. read()
            reader = new FileReader("src/com/lec206/ex03_reader/news.txt");
            int readData;
            while (true) {
                readData = reader.read();
                if (readData == -1)
                    break;
                System.out.println((char) readData);
            }
            reader.close();
            System.out.println();
     
            // 2. read(char[] cbuf)
            reader = new FileReader("src/com/lec206/ex03_reader/news.txt");
            int readCharNo;
            char[] cbuf = new char[2];
            String data = "";
            while (true) {
                readCharNo = reader.read(cbuf);
                if (readCharNo == -1)
                    break;
                data += new String(cbuf, 0, readCharNo);
            }
            System.out.println(data);
            reader.close();
            System.out.println();
     
            // 3. read(char[] buf, int off, int len)
            reader = new FileReader("src/com/lec206/ex03_reader/news.txt");
            int readNo;
            char[] cbuff = new char[8];
            readNo = reader.read(cbuff, 14);
            for (int i = 0; i < cbuff.length; i++) {
                System.out.println(cbuff[i]);
            }
            reader.close();
            System.out.println();
     
        }
    cs

    Output: Writer 문자 기반

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
        public static void main(String[] args) throws IOException {
            
            Writer writer = null;
            
            //1. write(char[])
            writer = new FileWriter("src/com/lec206/ex04_writer/sample.txt");
            char[] data = "대한민국만세".toCharArray();
            for(int i =0; i<data.length; i++) {
                writer.write(data[i]);
            }
            writer.flush();
            writer.close();
            
            //2. write(char[], int off, int len)
            writer = new FileWriter("src/com/lec206/ex04_writer/sample2.txt");
            data = "우리나라만세".toCharArray();
            writer.write(data,1,4);//리나라만
            writer.flush();
            writer.close();
        }
    cs

    파일입출력1: File클래스

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
        public static void main(String[] args) throws Exception {
     
            // d드라이브 밑에 파일및 txt파일 생성
            File dir = new File("d:/temp/dir");
            File file1 = new File("d:/temp/dir/file1.txt");
            File file2 = new File("d:/temp/dir/file2.txt");
            File file3 = new File(new URI("file:///d:/temp/dir/file3.txt"));
     
            if (dir.exists() == false)
                dir.mkdirs();
            if (file1.exists() == false)
                file1.createNewFile();
            if (file2.exists() == false)
                file2.createNewFile();
            if (file3.exists() == false)
                file3.createNewFile();
     
            //지정된 파일에 어떤 파일(폴더들)이 있는지 확인
            File temp = new File("d:/dojihye/02.java");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd                   HH:mm");
            File[] files = temp.listFiles();
            System.out.println("----------------------------------------------------");
            for (File file : files) {
                if (file.isDirectory()) {
                    System.out.println("\t<dir>\t" + file.getName());
                } else {
                    System.out.println("\t" + file.getName() + "\t" + file.length());
                }
            }
     
        }
     
    }
     
    cs

    파일입출력2: FileInputStream 클래스

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
        public static void main(String[] args) throws Exception {
     
            FileInputStream fis = new FileInputStream("src/com/lec206/ex05_file/FileMain.java");
            int data;
            while ((data = fis.read()) != -1) {
                System.out.println((char) data);
            }
            fis.close();
     
        }
    cs

    파일입출력3: FileOutputStream 클래스

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
        public static void main(String[] args) throws Exception {
     
            //이게 바로 내가 파일을 다운로드 받을 때의 과정이다.(복사해서 갖다줌)
            String orgFileName = "d:/temp/dir/bts01.jpg";
            String newFileName = "d:/temp/dir/bts01_copy.jpg";
     
            FileInputStream fis = new FileInputStream(orgFileName);
            FileOutputStream fos = new FileOutputStream(newFileName);
     
            int readByte;
            byte[] readBytes = new byte[100];
            while ((readByte = fis.read(readBytes)) != -1) {
                fos.write(readBytes, 0, readByte);
            }
            fos.flush();
            fos.close();
            fis.close();
            System.out.println("파일복사가 완료되었습니다.");
        }
    cs

    파일입출력4: FileReader 클래스

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
        public static void main(String[] args) throws Exception {
            
            FileReader fr = new FileReader("src/com/lec206/ex05_file/filemain.java");
            int readChar;
            char[] cbuf = new char[150];
     
            while ((readChar = fr.read(cbuf)) != -1) {
                String data = new String(cbuf, 0, readChar);
                System.out.println(data);
            }
            fr.close();
        }
     
    cs

    파일입출력5: FileWriter 클래스

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
        public static void main(String[] args) throws Exception {
            File file = new File("d:/temp/dir/야생화.txt");
            FileWriter fw = new FileWriter(file);
            
            fw.write("하얗게 피어난 얼음꽃 하나가 \n");
            fw.write("달가운 바람에 얼굴을 내밀어 \n");
            fw.write("아무말 못했던 이름도 몰랐던 \n");
            fw.write("지나간 날들에 눈물이 흘러 \n");
            fw.write("\n");
            fw.write("차가운 바람에 숨어있다 \n");
            fw.write("한줄기 햇살에 몸 녹이다\n");
            fw.write("그렇게 너는 또 한번 내게 온다. \n");
            fw.write(" \n");
            fw.write("좋았던 기억만 \n");
            fw.write("그리운 마음만 \n");
            fw.write("니가 떠나간 그 길 위에 \n");
            fw.write("이렇게 남아 서 있다. \n");
            fw.close();
            System.out.println("파일이 정상적으로 저장되었습니다.");
        }
    cs

    NIO1

    NIOPath

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
            // 1. Path
            Path path = Paths.get("src/com/lec206/01_file/NIOPathMain.java");
            System.out.println("파일이름    :" + path.getFileName());
            System.out.println("부모디렉토리:" + path.getParent().getFileName());
            System.out.println("중첩경로수  :" + path.getNameCount()); // 중첩된 경로파일들의 이름들(본인이름까지 포함)
            System.out.println();
     
            for (int i = 0; i < path.getNameCount(); i++) {
                System.out.println(path.getName(i));
            }
            System.out.println();
     
            // 위와 결과 똑같음
            Iterator<Path> iterator = path.iterator();
            while (iterator.hasNext()) {
                Path temp = iterator.next();
                System.out.println(temp);
            }
            System.out.println();
     
            System.out.println(path.toString());
     
            //IO보다는 많은 정보를 알려줌
    cs

    FileSystem

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
        public static void main(String[] args) throws Exception {
     
            // 2. FileSystem
            // getFileStores(): 드라이버정보를 가진 FileStores객체를 리턴
            // getRootDirectories(): 루트디렉토리정보를 가진 Path객체를 리턴
            // getSperator(): 디렉토리구분자를 리턴
     
            FileSystem fileSystems = FileSystems.getDefault();
     
            for (FileStore store : fileSystems.getFileStores()) {
                System.out.println("[드라이버명]\t" + store.name());
                System.out.println("[파일시스템]\t" + store.type());
                System.out.println("[전체메모리]\t" + store.getTotalSpace() + "bytes");
                System.out.println("[사용메모리]\t" + (store.getTotalSpace() - store.getUnallocatedSpace()));
                System.out.println("[가능메모리]\t" + store.getUsableSpace());
                System.out.println();
            }
            System.out.println("[파일구분자]\t" + fileSystems.getSeparator());
            System.out.println();
     
            for (Path path : fileSystems.getRootDirectories()) {
                System.out.println(path.toString());
            }
     
        }
    cs

    Path - Files

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
        public static void main(String[] args) throws Exception {
     
            // 3. 파일속성읽기 및 파일/디렉토리 생성,삭제
            Path path = Paths.get("src/com/lec206/ex01_file/FilesMain.java");
            
            System.out.println("[디렉토리여부]\t\t" + Files.isDirectory(path));
            System.out.println("[파일여부]\t\t" + Files.isRegularFile(path));
            System.out.println("[최종수정시간]\t\t" + Files.getLastModifiedTime(path));
            System.out.println("[파일크기]\t\t" + Files.size(path));
            System.out.println("[소유자]\t\t" + Files.getOwner(path));
            System.out.println("[숨김파일]\t\t" + Files.isHidden(path));
            System.out.println("[읽기파일]\t\t" + Files.isReadable(path));
            System.out.println("[쓰기파일]\t\t" + Files.isWritable(path));
     
        }
    cs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
        public static void main(String[] args) throws Exception {
            // Path에 만들 파일의 경로를 미리 집어놓고 Files로 있나 한번 살피고 생성.
            Path path1 = Paths.get("d:/temp/dir/subdir1");
            Path path2 = Paths.get("d:/temp/dir/한숨.txt");
     
            if (Files.notExists(path2)) {
                Files.createFile(path2);
            }
     
            if (Files.notExists(path1)) {
                Files.createDirectory(path1);
            }
     
            Path path3 = Paths.get("d:/temp");
            DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path3);
     
            for (Path path : directoryStream) {
                if (Files.isDirectory(path)) {
                    System.out.println(path.getFileName() + "<dir>");
                } else {
                    System.out.println(path.getFileName() + "(크기: " + Files.size(path) + ")");
                }
            }
     
        }
    cs

    Buffer

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    public class BufferSizeMain {
     
        public static void main(String[] args) {
     
            //운영체제가 관리하는 메모리공간에 버퍼
            ByteBuffer directBuffer = ByteBuffer.allocateDirect(200*1024*1024);
            System.out.println("다이렉트 버퍼를 생성");
            
            //JVM이 관리하는 메모리공간에 버퍼
            //컴퓨터의 성능과 현재메모리상태에 따라 OutOfMemoryError가 발생할 수 있다.
            ByteBuffer nonDirectBuffer = ByteBuffer.allocate(200*1024*1024);
            System.out.println("넌다이렉트 버퍼를 생성");
            
        }
    }
    cs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
        public static void main(String[] args) throws Exception {
     
            Path from = Paths.get("src/com/lec206/ex02_buffer/bts01.jpg");
            Path to1 = Paths.get("src/com/lec206/ex02_buffer/bts02.jpg");
            Path to2 = Paths.get("src/com/lec206/ex02_buffer/bts03.jpg");
            
            long size = Files.size(from);
            System.out.println(size);//195078 (byte단위)
            
            FileChannel fileChannelFrom = FileChannel.open(from);
            FileChannel fileChannelto1 = FileChannel.open(to1, EnumSet.of(StandardOpenOption.CREATE,StandardOpenOption.WRITE));
            FileChannel fileChannelto2 = FileChannel.open(to2, EnumSet.of(StandardOpenOption.CREATE,StandardOpenOption.WRITE));
            
            ByteBuffer nonDirectBuffer = ByteBuffer.allocate((int)size);
            ByteBuffer dircectBuffer = ByteBuffer.allocateDirect((int)size);
            
            long start, end;
            
            //NonDirect
            start = System.nanoTime();
            
            for(int i = 0; i<100; i++) {
                fileChannelFrom.read(nonDirectBuffer);
                nonDirectBuffer.flip();    //flip() 파일을 다시 처음부터 읽겠다.
                fileChannelto1.write(nonDirectBuffer);
                nonDirectBuffer.clear();
            }
            
            end = System.nanoTime();
            System.out.println("NonDirect 소요시간 = "+(end-start)+"ns");//NonDirect 소요시간 = 3054100ns
            
            
            // Direct
            start = System.nanoTime();
            
            for(int i = 0; i<100; i++) {
                fileChannelFrom.read(dircectBuffer);
                dircectBuffer.flip();    //flip() 파일을 다시 처음부터 읽겠다.
                fileChannelto2.write(dircectBuffer);
                dircectBuffer.clear();
            }
            
            end = System.nanoTime();
            System.out.println("Direct소요시간 = "+(end-start)+"ns");//Direct소요시간 = 1213700ns
     
        }
     
    cs

    filechannel

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
        public static void main(String[] args) throws Exception {
     
            Path path = Paths.get("d:/temp/dir/test.txt");
            Files.createDirectories(path.getParent());
     
            // FileChaennel 을 생성
            FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
            String data = "안녕하세요? 반갑습니다!"// 한글 3바이트, 공백,특수문자 1바이트씩
            Charset charset = Charset.defaultCharset();
            ByteBuffer buffer = charset.encode(data);
     
            // 파일에 쓰기
            int byteCount = fileChannel.write(buffer);
            System.out.println("text.txt : " + byteCount + " bytes 쓰기완료"); // text.txt : 33 bytes 쓰기완료
     
     
            fileChannel = FileChannel.open(path, StandardOpenOption.READ);
            buffer = ByteBuffer.allocate(100);
            data = "";
            byteCount = 0;
     
            // 파일 읽기
            while (true) {
                byteCount = fileChannel.read(buffer);
                if (byteCount == -1)
                    break;
                buffer.flip();    //position을 0위치로 이동
                data = charset.decode(buffer).toString();
                buffer.clear();
            }
            System.out.println(data);
            
            fileChannel.close();
     
        }
    cs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
        public static void main(String[] args) throws Exception {
     
            // 1. copy() 메서드를 이용하지 않고 파일복사하기
            Path from = Paths.get("src/com/lec206/ex02_buffer/bts01.jpg");
            Path to = Paths.get("src/com/lec206/ex03_filechannel/bts01.jpg");
     
            FileChannel fileChannel_from = FileChannel.open(from, StandardOpenOption.READ);
            FileChannel fileChannel_to = FileChannel.open(to, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
            ByteBuffer buffer = ByteBuffer.allocateDirect(100);
            int byteCount;
            while (true) {
                buffer.clear();
                byteCount = fileChannel_from.read(buffer);
                if (byteCount == -1)
                    break;
                fileChannel_to.write(buffer);
            }
            fileChannel_from.close();
            fileChannel_to.close();
     
            // 2. copy() 메서드를 이용헤 파일복사하기
            to = Paths.get("src/com/lec206/ex03_filechannel/bts_copy_1.jpg");
            Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("파일복사완료(Files.copy()");
     
        }
    cs

    'JAVA' 카테고리의 다른 글

    JAVA와 DBMS연결하기-JDBC  (0) 2021.07.24
    HTTP,Tomcat이론,JSP:스크립트요소  (0) 2021.07.23
    Collection FrameWork,Stream  (0) 2021.07.23
    Thread, Generic, Lambda, Collection Framework  (0) 2021.07.23
    정규표현식,Arrays,java.lang 패키지  (0) 2021.07.23

    댓글

Designed by Tistory.