✅네이버클라우드 캠프/개발일기

[네이버클라우드캠프] 44일차.자바 I/O (입출력) - 파일 및 데이터 처리

우동한그릇 2023. 6. 27. 21:13
반응형

 

 

* java.io.*, java.nio.*

 

① File 클래스 →  ② Binary I/O 클래스  →  ③ Data Processing 클래스

④ character I/O 클래스 →  ⑤ JSON 형식으로 I/O

 

 

* File 클래스

 

① File 클래스 - 폴더 생성


    // 디렉토리를 생성할 때 존재하지 않는 중간 디렉토리도 만들고 싶다면,
    // mkdirs()를 호출하라.
    //
    // mkdirs()
    // - 지정된 경로에 디렉토리가 존재하지 않으면 그 디렉토리도 만든다.
    //

// 디렉토리 생성
package io.ex01;

import java.io.File;

public class Exam0322 {

  public static void main(String[] args) throws Exception {

    File dir = new File("temp2/a/b");

    if (dir.mkdirs()) {
      System.out.println("temp2/a/b 디렉토리를 생성하였습니다.");
    } else {
      System.out.println("temp2/a/b 디렉토리를 생성할 수 없습니다.");
    }


  }

}

 

 

① File 클래스 - 폴더 삭제

 

      // 디렉토리 안에 파일이나 다른 하위 디렉토리가 있다면 삭제할 수 없다.
      // 또한 존재하지 않는 디렉토리도 삭제할 수 없다.

// 디렉토리 삭제
package io.ex01;

import java.io.File;

public class Exam0330 {

  public static void main(String[] args) throws Exception {

    File dir = new File("temp");

    if (dir.delete()) {
      System.out.println("temp 디렉토리를 삭제하였습니다.");
    } else {
      // 디렉토리 안에 파일이나 다른 하위 디렉토리가 있다면 삭제할 수 없다.
      // 또한 존재하지 않는 디렉토리도 삭제할 수 없다.
      System.out.println("temp 디렉토리를 삭제할 수 없습니다.");
    }
  }

}

 

* File과 FilenameFilter

 

* 익명 함수로 만들고 람다 함수 적용해보기

// 디렉토리에 들어있는 파일(디렉토리) 목록을 꺼낼 때 필터 적용하기 II
package io.ex01;

import java.io.File;
import java.io.FileFilter;

public class Exam0620x {
  public static void main(String[] args) throws Exception {
    class JavaFilter implements FileFilter {
      @Override
      public boolean accept(File file) {
        if (file.isFile() && file.getName().endsWith(".java"))
          return true; // 조회 결과에 포함시켜라!
        return false; // 조회 결과에서 제외하라!
      }
    }
    File dir = new File(".");
    JavaFilter javaFilter = new JavaFilter();
    File[] files = dir.listFiles(javaFilter);
    for (File file : files) {
      System.out.printf("%s %12d %s\n", file.isDirectory() ? "d" : "-", file.length(),
          file.getName());
    }

  }

}
// 디렉토리에 들어있는 파일(디렉토리) 목록을 꺼낼 때 필터 적용하기 II
package io.ex01;

import java.io.File;
import java.io.FileFilter;

public class Exam0621x {
  public static void main(String[] args) throws Exception {
    File dir = new File(".");

    File[] files = dir.listFiles(new FileFilter() {
      @Override
      public boolean accept(File file) {
        return file.isFile() && file.getName().endsWith(".java");
      }
    });

    for (File file : files) {
      System.out.printf("%s %12d %s\n", file.isDirectory() ? "d" : "-", file.length(),
          file.getName());
    }

  }

}
// 디렉토리에 들어있는 파일(디렉토리) 목록을 꺼낼 때 필터 적용하기 II
package io.ex01;

import java.io.File;

public class Exam0621x2 {
  public static void main(String[] args) throws Exception {
    File dir = new File(".");
    File[] files = dir.listFiles(file -> file.isFile() && file.getName().endsWith(".java"));

    for (File file : files) {
      System.out.printf("%s %12d %s\n", file.isDirectory() ? "d" : "-", file.length(),
          file.getName());
    }

  }

}

 

 

* // FileInputStream 활용 - JPEG 파일 읽기 : 위도/경도 알아내기

 

package com.eomcs.io.ex02;

import java.io.File;
import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.GpsDirectory;

public class Exam0420 {

  public static void main(String[] args) throws Exception {

    File file = new File("sample/gps-test.jpeg");

    Metadata metadata = ImageMetadataReader.readMetadata(file);
    GpsDirectory gpsDirectory = metadata.getFirstDirectoryOfType(GpsDirectory.class);

    if (gpsDirectory != null) {
      // 사진 파일에 GPS 정보가 있을 경우,
      System.out.println(gpsDirectory.getGeoLocation().getLatitude());
      System.out.println(gpsDirectory.getGeoLocation().getLongitude());
    }

  }

}

 

패키지를 import 하기 위해서 의존성을 주입해야하므로

build.gradle 에 아래 문구를 추가해준다.

 

  // 미디어 파일에서 메타정보 추출
    implementation 'com.drewnoakes:metadata-extractor:2.18.0'

 

 

그 후 해당 파일이 있는 폴더경로에 gradle eclips 명령어를 통해서

변경사항을 적용해주도록 한다.

 

 

Refresh를 통해서 새로고침을 해준다.

 

 

 

수정된 파일을 실행해주면 성공적으로 위도와 경도가 출력된다.

 

 


* binary file / text file 

 

반응형