ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Java - File I/O
    Java 2018. 2. 1. 14:30
    반응형
    // java에서 파일이나 폴더를 다루려면 java.io.File 객체가 필요 하다.


    < mkdir, createNewFile, list >


    import java.io.File;
    import java.io.IOException;

    public class FileMain {

        public static void main(String[] args) throws IOException {
            
            // 폴더 생성
            File dir = new File("C:/img");
            if(!dir.exists()) {
                System.out.println("폴더가 없네요");
                dir.mkdir(); // 만들기
            }
            
            // 파일 생성
            File file = new File("C:/img/test.txt");
            if(!file.exists()) {
                System.out.println("파일이 없네요");
                file.createNewFile();
            }
            
            // 폴더 정보 알아보기
            String[] files = dir.list(); // 해당 폴더 안의 파일 명을 반환 한다.
            for(String f : files) {
                System.out.println(f);
            }
            
            File[] fileObjs = dir.listFiles(); // 해당 폴더 안의 파일 객체를 반환
            String gubun = "파일";
            for(File obj : fileObjs) {
                if(obj.isDirectory()==true) {
                    gubun = "폴더";
                }
                System.out.println(gubun+"/"+obj.getName()+"/"+obj.length()+"byte");
            }
            
        }

    }



    // 1. 읽어올 파일 위치를 설정 한다.
    // 2. 파일을 객체화 한다.
    // 3. 읽어올 때 필요한 STream을 준비 한다.
    // 4. 한 글자 씩 읽어와 출력한다
    // 5. 사용한 자원을 닫는다.


    < FileInput >

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;

    public class FileInputMain {

        public static void main(String[] args) throws Exception {
            
            // 1. 파일 위치 설정
            String path = "C:/img/news.txt";
            // 2. 파일 객체 생성
            File file = new File(path);
            // 3. 읽어올 때 필요한 Stream 준비
            FileInputStream fis = new FileInputStream(file);
            // 4. 읽어서 출력
            int data;
            while((data = fis.read()) != -1) { // 오류가 나거나 파일이 끝나면 -1을 반환
                System.out.print((char)data);
            }
            // 5. 다 사용한 후 닫는다.
            fis.close();
            
        }

    }





    < FileOutput >


    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;

    public class FileOutMain {

        public static void main(String[] args) throws Exception {
            
            // 1. 불러올 파일과 내보낼 파일 위치 지정
            String oriPath = "C:/img/coffee.jpg";
            String targetPath = "D:/copy.jpg";
            // 2. 스트림 준비
            FileInputStream fis = new FileInputStream(oriPath);
            // true면 기존파일에 이어 쓴다.
            FileOutputStream fos = new FileOutputStream(targetPath, false);
                                                
            // 3. 파일 읽어오기
    //        int data;
    //        while((data = fis.read()) != -1) {
    //            fos.write(data); // 4. 파일 쓰기
    //        }

    int i = 0;
    byte[] b = new byte[1024];
    while(fis.read(b) != -1) {
       fos.write(b); // byte를 계속 던져서 파일을 쓴다.
                         // 속도는 이게 더 빠르다
        i++;
    }
    System.out.println("반복 횟수 : "+i);
            // 5. 닫는다 - 닫기전 flush
            fos.flush();
            fos.close();
            fis.close();

        }

    }


    < FileRead >


    import java.io.FileReader;
    import java.io.FileWriter;

    public class FileRead {

        public static void main(String[] args) throws Exception {
            
            // 1. 가져올 위치 지정
            String path = "C:/img/news.txt";
            String targetPath = "D:/newsCopy.txt";
            // 2. 스트림준비(파일 객체의 생략)
            FileReader reader = new FileReader(path);
            FileWriter writer = new FileWriter(targetPath);
            // 3. 읽어 오기 -> 출력
            
            int data;
            while((data = reader.read()) != -1) {
                System.out.print((char)data);
            }
            
            // 4. 반납
            reader.close();

        }

    }




    < FileWrite >

    import java.io.FileWriter;

    public class FileWrite {

        public static void main(String[] args) throws Exception {
            
            // 1. 저장할 파일 위치
            String path = "C:/img/test.txt";
            // 2. 스트림 준비
            FileWriter writer = new FileWriter(path, true); // true면 이어서 쓰기
            // 3. 파일에 문자 쓰기
            writer.write("for문 시작\r\n");
            for(int i=1;i<=25;i++) {
                writer.write("Data : "+i+"\r\n");
            }
            writer.write("for문 종료\r\n");
            // 4. flush(), 자원 반납
            writer.flush();
            writer.close();
            
        }

    }





    import java.io.File;
    import java.io.FileWriter;
    import java.util.Scanner;

    public class TestIO {

        public static void main(String[] args) throws Exception {
            
            // 1. 내보낼 파일 위치 설정
            File file = new File("D:/sample.txt");
            if(!file.exists()) {
                System.out.println("파일이 없네요");
                file.createNewFile(); // 만들기
            }
            String targetPath = "D:/sample.txt";
            // 2. 내용을 불러올 Scanner 준비
            Scanner scan = new Scanner(System.in);
            System.out.println("내용을 입력해 주세요 : ");
            // 3. 파일로 내보낼 File Writer 준비
            FileWriter writer = new FileWriter(targetPath, true);
            // 4. 입력 내용을 읽어 온다.
            String s = scan.nextLine();
            
            // 5. 읽어온 내용을 파일로 내보낸다
            writer.write(s);
            
            // 6. 사용한 자원 반납
            writer.flush();
            writer.close();
            
        }

    }







    반응형

    'Java' 카테고리의 다른 글

    Java - Network  (0) 2018.02.05
    Java - Stream IO  (0) 2018.02.02
    Java - Java I/O  (0) 2018.02.01
    Mac에서 이클립스로 C언어 프로그래밍하기  (0) 2018.02.01
    Java - Thread Pool, Thread Pool Blocking  (0) 2018.01.31

    댓글

Designed by Tistory.