본문 바로가기

Contact 日本語 English

【Java】 7강. File I/O

 

7강. File I/O

 

추천글 : 【Java】 Java 목차 


1. java.io.File class [본문]

2. Scanner class [본문]

3. InputStream class [본문]

4. OutputStream class [본문]

5. FileReader class [본문]

6. FileWrite class [본문]


a. GitHub 


 

1. java.io.File class [목차]

java.nio.file 패키지는 더 나은 exception handling을 제공함

 예 1. 디렉토리 내 file들을 list-up하는 코드 : FileNotFoundException이 없어도 가능

 

import java.io.File;

public class Main{
  public static void main(String[] args){
    File directory = new File("C:/Users/");
    File[] directoryFiles = directory.listFiles();

    for(int i = 0; i < directoryFiles.length; i ++)
      System.out.println(directoryFiles[i].getName());
  }
}

 

⑶ 예 2. creation / deletion / rename : FileNotFoundException 처리가 필수적

예 3. copy 

 

public void FileIOCopy(String source, String dest) throws FileNotFoundException, IOException{
    FileInputStream fis = new FileInputStream(source);
    FileOutputStream fos = new FileOutputStream(dest);
    int availableLen = fis.available();
    byte[] buf = new byte[availableLen];
    fis.read(buf);
    fos.write(buf);
}

 

 

2. Scanner class [목차]

Scanner class로 file을 reading하는 코드

 

static void readFile(){
  File testFile = new File("data/say_hello.txt");
  try {
    Scanner input = new Scanner(file);
    while (input.hasNext()) {
      System.out.println(input.nextLine());
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}

 

 

3. InputStream class [목차]

⑴ InputStream의 종류

 FileInputStream 

 PipedInputStream 

 FilterInputStream 

 ByteArrayInputStream 

 SequenceInputStream 

 StringBufferedInputStream 

 ObjectInputStream 

 System.in

⑵ ByteArrayInputStream의 종류

 LineNumberInputStream 

 DataInputStream 

 BufferedInputStream 

 PushbackInputStream  

⑶ method

  int read(); // 실행할 때마다 stream에 다음 byte를 읽게 됨. 읽을 때는 (char)로 casting할 것

 int read(byte[] b); // multiple bytes를 한 번에 읽기 위해 사용됨

int read(byte[] b, int off, int len); 

 void close(); // 특정 file과 관련된 새로운 작업을 하기 위해 기존 작업을 종료

 

 

4. OutputStream class [목차]

⑴ OutputStream의 종류

 FileOutputStream 

 PipedOutputStream 

 FilterOutputStream 

 ByteArrayOutputStream 

 ObjectOutputStream 

⑵ FilterOutputStream의 종류

 DataOutputStream 

 BufferedOutputStream // 더 효율적으로 출력할 것을 grouping

 PrintStream 

⑶ method 

 void write(int i);

 void write(byte buf[]);

 void write(byte buf[], int index, int size);

 void close(); // 특정 file과 관련된 새로운 작업을 하기 위해 기존 작업을 종류

 void flush(); // 버퍼에서 기다리지 말고 당장 write하라는 의미. 대체로 프로그램이 끝날 때 heap이 flush됨

 

 

5. FileReader class [목차]

method

 public int read(); 

 public int read(char[] c, int offset, int len);

 

 

6. FileWriter class [목차]

OutputStreamintbyte[]를 객체로 하는 반면, FileWriterString이나 char[]를 객체로 함

method

 .write(String string); // overwrite

 .append(String string); // add to existing file 

⑶ 예제 

 

public static void writeLines(String fName, List<String> l)
throws IOException {
  FileWriter fileWriter = null;
  try {  
    fileWriter = new FileWriter(fName);
    for (String string : l) {
      fileWriter.write(string + "\n");
    }
  } catch (IOException e) {
    e.printStackTrace();
  } finally {
    if(fileWriter != null)
      fileWriter.close();
  }
}

 

FileOutputStream을 이용하려면 fileOutputStream(string.getBytes());처럼 getBytes()만 추가하면 됨 

 

입력: 2020.10.28 16:03

'▶ 자연과학 > ▷ Java' 카테고리의 다른 글

【Java】 9강. 기타 문법  (0) 2020.11.04
【Java】 8강. Exception  (0) 2020.11.02
【Java】 6강. 자료구조  (0) 2020.10.20
【Java】 Java 목차  (0) 2020.09.23
【Java】 5강. 다형성(polymorphism)  (0) 2020.09.23