자바/이론(Theory)

DAY010. JAVA(5)

피톤치즈 2017. 1. 20. 20:37
반응형

JAVA(5)

//선언
Path path = Paths.get(directory, filename);

//읽기
byte[] bytes = Files.readAllBytes(path);
String content = new String(bytes, StandardCharsets.UTF_8);
List<String> lines = Files.readAllLines(path);

//쓰기
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
  • 파일처리 예(1. 버퍼사용하여 입출력)
    /** 파일 쓰기
     *     BufferedWriter 사용하여 저장
     */
    public void writeFile()    {
        String path = "c:\\input\\test"; //디렉토리 경로
        String fileName = "c:\\input\\test\\test01.txt"; //파일 전체 경로

        File dir = new File(path);
        if ( dir.exists()) {    //디렉토리가 없으면...
            //dir.mkdir();    // 마지막 디렉토리만 생성
            dir.mkdirs();    // 경로상의 디렉토리가 없으면 모든 디렉토리 생성
        }

        File outFile = new File(fileName);
        if ( outFile.exists()) {    //같은 파일 네임이 있으면..
            System.out.println("같은 파일이 존재");
        }
        else {
            //try with방법으로 ...
            try ( BufferedWriter bw = new BufferedWriter(new FileWriter(fileName)))    {
                String content = "작성내용";
                bw.write(content);
                bw.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /** 파일 읽기
     * BufferedReader 사용하여 읽기
     */
    public void readFile()    {
        String path = "c:\\input\\test"; //디렉토리 경로
        String fileName = "c:\\input\\test\\test01.txt"; //파일 전체 경로

        File inFile = new File(fileName);

        //유효성 체크
        if (inFile.exists()) {    //파일이 있으면
            //tryWith
            try ( BufferedReader br = new BufferedReader(new FileReader(inFile))) {
                String line;
                while( (line = br.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {    //파일 없으면
            System.out.println("파일 없음");
        }
    }
  • 파일처리 예(2. stream 사용하여 입출력)
    /** 파일 쓰기
     * FileOutputStream 사용하여 쓰기
     */
    public void writeStream()    {
        String path = "c:\\input\\test"; //디렉토리 경로
        String fileName = "c:\\input\\test\\test01.txt"; //파일 전체 경로

        File dir = new File(path);
        if ( dir.exists()) {    //디렉토리가 없으면...
            //dir.mkdir();    // 마지막 디렉토리만 생성
            dir.mkdirs();    // 경로상의 디렉토리가 없으면 모든 디렉토리 생성
        }

        File outFile = new File(fileName);
        if ( outFile.exists()) {    //같은 파일 네임이 있으면..내용 추가
            try (FileOutputStream fos = new FileOutputStream(fileName, true)) {
                String content = "작성할 내용이 여기임...";
                fos.write(content.getBytes());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else {    //같은 파일 네임이 없으면..파일 생성
            try (FileOutputStream fos = new FileOutputStream(fileName)) {
                String content = "작성할 내용이 여기임...";
                fos.write(content.getBytes());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /** 파일 읽기 : 1 Line씩 읽기
     *
     */
    public void readStream3() {
        String path = "c:\\input\\test"; //디렉토리 경로
        String fileName = "c:\\input\\test\\test01.txt"; //파일 전체 경로

        File file = new File(fileName);
        //파일이 있으면
        if ( file.exists()) {
            try (BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"))) {
            // 파일 인코딩을 지정할때 UTF-8을 쓸것.
                String line;    //file에서 1줄씩 읽어옴
                while((line = fis.readLine()) != null)    {
                    System.out.println(line);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else {
            System.out.println("파일 없음");
        }
    }

    /** 파일 읽기 : byte[]의 사이즈 만큼
     *
     */
    public void readStream2() {
        String path = "c:\\input\\test"; //디렉토리 경로
        String fileName = "c:\\input\\test\\test01.txt"; //파일 전체 경로
        File file = new File(fileName);

        //파일이 있으면
        if ( file.exists()) {
            try (FileInputStream fis = new FileInputStream(fileName)) {
                byte[] byArr = new byte[10];
                int count = 0;
                //byArr사이즈 만큼 읽어옴.
                while((count = fis.read(byArr)) != -1)    {
                    for ( int j = 0; j < count; j++ ) {
                        System.out.println((char)byArr[j]); //한글이 안나옴.
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else {
            System.out.println("파일 없음");
        }
    }

    /** 파일 읽기 : 1byte씩
     *
     */
    public void readStream1() {
        String path = "c:\\input\\test"; //디렉토리 경로
        String fileName = "c:\\input\\test\\test01.txt"; //파일 전체 경로

        File file = new File(fileName);

        //파일이 있으면
        if ( file.exists()) {
            try (FileInputStream fis = new FileInputStream(fileName)) {
                int i = -1;
                while((i = fis.read()) != -1)    { //1byte씩 읽어옴.
                    System.out.println((char)i);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else {
            System.out.println("파일 없음");
        }
    }
  • 파일처리 예(3. NIO 사용하여 입출력)
    /** 파일 읽기
     *
     */
    public void readNio() {
        String dir = "c:\\input\\test"; //디렉토리 경로
        String fileName = "c:\\input\\test\\test01.txt"; //파일 전체 경로
        Path path = Paths.get(dir, filename);

        try {
            byte[] bytes = Files.readAllBytes(path);//파일의 모든 내용
            String content = new String(bytes, StandardCharsets.UTF_8); //인코딩방식 지정
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 파일 쓰기
     *
     */
    public void writeNio(Bbs data) {
        String dir = "c:\\input\\test"; //디렉토리 경로
        String fileName = "c:\\input\\test\\test01.txt"; //파일 전체 경로
        Path path = Paths.get(dir, filename);

        String tmp = "";
        try {
            Files.write(path, tmp.getBytes(StandardCharsets.UTF_8, StandardOpenOption.CREATE,StandardOpenOption.APPEND));//파일을 쓸때 생성하거나 내용추가.
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

특이사항

  • StringBuffer와 StringBuilder에 대해서 추후 다시 공부.
  • IO / NIO 추후에 다시 공부해볼것
  • 파일 입출력(NIO방식) 이용한 게시판 관리 프로그램 만들어보기.
반응형