。゚(*´□`)゚。

코딩의 즐거움과 도전, 그리고 일상의 소소한 순간들이 어우러진 블로그

[네이버클라우드] 클라우드 기반의 개발자 과정 7기/웹프로그래밍

[NC7기-44일차(6월27일)] - 웹프로그래밍 25일차

quarrrter 2023. 6. 27. 14:19

Data I/O stream API

 

I/O Stream API

package: java.io.* , java.nio.*

1. file 클래스 사용법 
file 클래스: file을 다루는 도구 
2. Binary data  I/O  (입출력 ) 클래스 사용법
bite 단위로 I/O 
대표 클래스 : FileInputStream, FileOutputStream
3. Data Processing 클래스 사용법
Stream(데이터 흐름: 데이터를 읽고 쓰는 것) 중간에서 데이터를 가공하는 것
사용 클래스:
Buffered Input Stream, Buffered Output Stream
DataInputStream , Data Output Stream : 바이트 단위로 쪼개는거,
Object Input Stream, Object Output Stream: 객체를 읽고 쪼개기
4. Character I/O 클래스
문자 단위로 I/O
사용 클래스"
FileReader, FileWriter
BufferedReader, BufferedWriter 
5. JSON 형식으로 I/O
외부라이브러리를 이용해서 I/O
외부라이브러리 : Gson, Jackson 

 

java.io.File 클래스
=> 파일이나 디렉토리 정보를 관리 (생성,삭제,변경)
File currentDir = new File("./src/main/java");
System.out.printf("폴더명: %s\n", currentDir.getName());
System.out.printf("경로: %s\n", currentDir.getPath());
System.out.printf("절대경로: %s\n", currentDir.getAbsolutePath());
System.out.printf("계산된 절대경로: %s\n", currentDir.getCanonicalPath());


System.out.printf("총크기: %d\n", currentDir.getTotalSpace());
System.out.printf("남은크기: %d\n", currentDir.getFreeSpace());
System.out.printf("가용크기: %d\n", currentDir.getUsableSpace());


System.out.printf("디렉토리여부: %b\n", currentDir.isDirectory());
System.out.printf("파일여부: %b\n", currentDir.isFile());
System.out.printf("감춤폴더: %b\n", currentDir.isHidden());
System.out.printf("존재여부: %b\n", currentDir.exists());
System.out.printf("실행가능여부: %b\n", currentDir.canExecute());
폴더명: java
경로: .\src\main\java
절대경로: C:\Users\bitcamp\git\bitcamp-study\java-lang\app\.\src\main\java
계산된 절대경로: C:\Users\bitcamp\git\bitcamp-study\java-lang\app\src\main\java
총크기: 255035699200  // 7자리 : 메가, 
남은크기: 128528314368
가용크기: 128528314368
디렉토리여부: true
파일여부: false
감춤폴더: false
존재여부: true
실행가능여부: true
 
File file1 = new File("./src/main/java/Hello2.java");
System.out.printf("파일명: %s\n", file1.getName());
System.out.printf("파일크기: %d\n", file1.length());
System.out.printf("경로: %s\n", file1.getPath());
System.out.printf("절대경로: %s\n", file1.getAbsolutePath());
System.out.printf("계산된 절대경로: %s\n", file1.getCanonicalPath());


// 존재하지 않는 폴더인 경우 크기를 알아낼 수 없다.
System.out.printf("총크기: %d\n", file1.getTotalSpace());
System.out.printf("남은크기: %d\n", file1.getFreeSpace());
System.out.printf("가용크기: %d\n", file1.getUsableSpace());


// 존재하지 않는 폴더인 경우 정보를 알아낼 수 없다. 모두 false
System.out.printf("디렉토리여부: %b\n", file1.isDirectory());
System.out.printf("파일여부: %b\n", file1.isFile());
System.out.printf("감춤여부: %b\n", file1.isHidden());
System.out.printf("존재여부: %b\n", file1.exists());
System.out.printf("실행가능여부: %b\n", file1.canExecute());
 
파일명: Hello2.java
파일크기: 76
경로: .\src\main\java\Hello2.java
절대경로: C:\Users\bitcamp\git\bitcamp-study\java-lang\app\.\src\main\java\Hello2.java
계산된 절대경로: C:\Users\bitcamp\git\bitcamp-study\java-lang\app\src\main\java\Hello2.java
총크기: 255035699200
남은크기: 128530644992
가용크기: 128530644992
디렉토리여부: false
파일여부: true
감춤여부: false
존재여부: true
실행가능여부: true
 

 

충격: 자바에서도 폴더 생성 가능 ; 

// 1) 생성할 디렉토리 경로 설정 - 폴더 경로를 지정하지 않으면 현재 폴더를 의미한다.
File dir = new File("temp");
dir.mkdir() ;// 디렉토리 생성

File dir = new File("temp/a"); //하위 디렉토리 생성하기

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

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

File dir = new File("temp");
dir.delete()
디렉토리 안에 파일이나 다른 하위 디렉토리가 있다면 삭제할 수 없다
생성할 파일의 경로 설정
 File file = new File("temp2/a/test.txt");

file
.createNewFile() // 파일 생성
 존재하지 않는 폴더에 파일을 생성할 때 해당 경로에 디렉토리가 없다면 파일을 생성할 수 없다.
file.delete() // 파일 삭제


// 특정 폴더를 생성하여 그 폴더에 파일을 만든다.
// 생성할 파일의 경로 설정
File file = new File("temp/b/test.txt");

// 파일을 생성하기 전에 존재하지 않는 폴더를 생성하고 싶다면,
File dir = file.getParentFile(); 
System.out.println(dir.getCanonicalPath());

// 먼저 디렉토리를 생성한다.
dir.mkdirs()

// 그런 후 파일을 생성한다.
file.createNewFile()
// 현재 폴더의 정보를 알아낸다.
File dir = new File(".");

For문으로 돌려서 다 출력 

// 현재 폴더에 있는 파일이나 하위 디렉토리 이름을 알아내기
String[] names = dir.list();

// 파일이나 디렉토리 정보를 File 객체로 받기
=> File은 디렉토리와 파일을 통칭하는 용어다.
File[] files = dir.listFiles();
file.isDirectory() ? "d" : "-",

 

 

file과 filenameFilter

file클래스  일시적인관계 dependency 관계
특정 메서드를 실행할 때
사용하는 의존 객체 
- - - - - - - - - - - - - - - - - - - - - - - - - - >

filenameFilter : 인터페이스
public static void main(String[] args) throws Exception {


class JavaFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {


// 해당 이름이 디렉토리 이름인지 파일 이름인지 알아내려면 File 객체를 생성해야 한다.
File file = new File(dir, name);
// 디렉토리 정보와 이름을 합쳐 파일 객체를 생성할 수 있다.

return file.isFile() && name.endsWith(".java") ; 
}

File dir = new File(".");


// => 확장자가 .java 인 파일의 이름만 추출하기
// 1) 필터 준비
JavaFilter javaFilter = new JavaFilter();


// 2) 필터를 사용하여 디렉토리의 목록을 가져오기
String[] names = dir.list(javaFilter);


for (String name : names) {
System.out.println(name);
} }

 

FileFilter - 인터페이스를 구현한 class 

파일객체 통채로 전달 

public class Exam0620 {



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


class JavaFilter implements FileFilter {
@Override
public boolean accept(File file) {
// 이 메서드는 listFiles() 메서드에서 호출한다.
// 지정한 폴더에 들어 있는 파일이나 디렉토리를 찾을 때 마다 호출한다.
// 리턴 값 File[] 에 찾은 파일 정보를 포함시킬지 여부를 결정한다.
// true 이면 배열에 포함시키고,
// false 이면 배열에서 제외한다.
//
return file.isFile() && file.getName().endsWith(".java");
}
}


File dir = new File(".");


// => 확장자가 .java 인 파일의 이름만 추출하기
// 1) 필터 준비
JavaFilter javaFilter = new JavaFilter();


// 2) 필터를 사용하여 디렉토리의 목록을 가져오기
File[] files = dir.listFiles(javaFilter);


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


}

 

FileFilter를 구현한 클래스를 만들고 익명클래스이기 때문에 바로 인스턴스 생성 

인터페이스 레퍼런스 선언하면 됨 ,,,,

 

람다문법

인터페이스이고, 추상메서드가 1개인 경우 사용가능 

// 메서드 한 개짜리 인터페이스인 경우
// 람다(lambda) 문법을 사용하면 훨씬 더 간결하게 코드를 작성할 수 있다.
//
// lambda class
// => 메서드가 한 개짜리인 경우 lambda 표현식을 사용할 수 있다.
// => 문법:
// (파라미터, 파라미터, ...) -> 문장 한개
// (파라미터, 파라미터, ...) -> { 문장1; 문장2; 문장3;}
// () -> 문장 한개
// () -> {문장1; 문장2; 문장3;}
//
File[] files = dir.listFiles(file -> {
return file.isFile() && file.getName().endsWith(".java");

});