18일차(스트림 연습문제, 파일 입출력)

Rina's·2023년 5월 4일

코드스테이츠

목록 보기
17/96

🍧파일 입출력

InputStream과 OutputStream
File을 다룰 때는 FileInputStream / FileOutputStream
프로세스를 다룰 때는 PipedInputStream / PipedOutputStream

FileInputStream(load)

        try {
            FileInputStream fileInput = new FileInputStream("codestates.txt");
            BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
            "codestates.txt"를 매개변수로 가지는 파일객체 fileInput생성
            int i = 0;
            while ((i = fileInput.read()) != -1) { 
            //값을 fileInput.read()로 불러들여 i에 저장한 후, 값이 -1인지 확인
                System.out.print((char)i);
            }//값이 있으면 문자 출력(형변환 안화면 아스키코드 출력)
            fileInput.close(); //파일 닫기
        }
        catch (Exception e) {
            System.out.println(e);
        }

FileInputStream 타입의 객체 생성
fileInput.read() 로 데이터 호출
while문으로 데이터가 있으면 char타입으로 print

BufferedInputStream : 성능을 올려주는 보조 스트림(임시 저장공간)

FileOutputStream(save)

        try {
            FileOutputStream fileOutput = new FileOutputStream("codestates.txt");
            //만들 파일 객채 fileOutput 생성
            String word = "code"; //txt에 넣을 문자열 생성

            byte b[] = word.getBytes(); //문자열을 바이트 배열로 저장
            fileOutput.write(b); //fileOutput에 바이트 배열 쓰기 
            fileOutput.close(); //fileOutput 닫기
        }
        catch (Exception e) {
            System.out.println(e);
        }

FileOutputStream 타입으로 파일 객체 생성
파일에 넣을 String 객체 생성
객체를 byte[] 로 변환, write()로 객체 쓰기, close()

문자기반 스트림

FileReaderFileWriter는 Java I/O패키지 제공 클래스로
스트림으로 읽어올 수 있게 한다
스트림 타입으로 바꿔 문자기반의 스트림 메서드를 사용해 보자!

FileReader 인코딩-> 유니코드
FileInputStream 에 대응

FileWriter 유니코드 -> 인코딩
FileOutputStream 에 대응

File 클래스

File 클래스로 파일 객체를 생성해 파일과 디렉토리에 접근 해 보자

public class FileExample {
    public static void main(String args[]) throws IOException {
            File file = new File("../codestates.txt");

            System.out.println(file.getPath());
            System.out.println(file.getParent());
            System.out.println(file.getCanonicalPath());
            System.out.println(file.canWrite());
    }
}

파일을 생성하기 위해서는 createNewFile() 메서드를 사용해야 한다

File file = new File("./", "newCodestates.txt"); 
//File 인스턴스 생성, 경로와 이름을 인수로 가짐
file.createNewFile();

renameTo()는 파일명을 바꾸고 boolean값을 리턴한다

        File file = new File("old_file_name.txt");
        File newFile = new File("new_file_name.txt");
        if (file.renameTo(newFile)) {
            System.out.println("File name changed successfully.");
        } else {
            System.out.println("File name changing failed.");
        }

🍦연습문제(Stream)

Q. 매핑(Mapping)

하나의 값에서 다른 값으로 대응시키는 것
map() mapToInt() mapToDouble() flatMap()대표적인 메서드

Q. flatMap()

List<String> list = Arrays.asList("apple", "banana");
List<String> flatList = list.stream()
						.flatMap(s -> Arrays.stream(s.split("")))
						.collect(Collectors.toList());
//결과 [ a, p, p, l, e, b, a, n, a, n, a, o, r, a, n, g, e ]
List<String> list = Arrays.asList("apple", "banana");
List<String> flatList = list.stream()
						.flatMap(s -> s.split(""))
						.collect(Collectors.toList());
//결과 [apple, a, p, p, l, e, banana, b, a, n, a, n, a]

😫😫😫

Q. Optional

sum()은 기본적으로 int값을 반환하나 Stream 내에 요소가 존재하지 않는 경우 OptionalInt 객체를 반환한다. 이는 int 값을 포함하거나, 비어있을 수 있는 래퍼 클래스이다
orElse(default) / isPresent() getAs<T>() 함수와 자주 사용한다

값이 없을 경우 getAs<T>()NoSuchElementException를 발생시킨다
이를 위해 사용하는 isPresent()는 Optional클래스의 iv메소드이므로 객체생성 후 조건문을 사용하거나 .filter(Optional<T>::isPresent)로 사용해야 한다

Optional을 리턴하는 Stream 메서드
sum(): int or OptionalInt
count(): long or OptionalLong
average(): double or OptionalDouble
max(): Optional (T는 요소타입 int, double등...)
min(): Optional

Q. orElse()

sum()이 빈 요소를 받을 경우 '0'을 리턴하는 것과 달리
average()OptionalDouble.empty()를 리턴한다. 이를 처리하기 위해 orElse()를 써 줘야 한다.

orElse(null)은 null safety를 보장하지 않아 Integer를 반환해야 한다
한마디로 리턴값이 int이면 orElse(null)을 못쓴다
굳이 쓰고싶다면

return Arrays.stream(arr).boxed()
						 .max(Integer::compareTo)
						 .orElse(null);

Q. mapToInt()

mapTo<T>()를 쓸 경우 Optional대응을 꼭 하자

Stream타입을 mapToInt()로 형변환 하고 collect(Collectors.toList())쓰면 매개변수 달라서 오류남(Stream의 collect는 1개, IntStream의 collect는 3개)
사용하고 싶으면 .boxed() 사용 해야함

Q. 자주 사용하는 메서드

Arrays.asList() 배열을 List로
list.toArray(arr2) List를 배열로
toArray(String[]::new) Stream을 배열로
collect(Collectors.toList()) Stream을 List로

filter() 매개변수 까먹지 말기
Stream.concat() 매서드 호출시 클래스명 사용유무 확인하기

Q. 메서드 참조

람다식에서 사용되는 매개변수와 반환값의 타입이 일치할것

인스턴스 메서드: 객체 레퍼런스::메서드명 또는 클래스명::메서드명
클래스 메서드: 클래스명::메서드명
생성자: 클래스명::new

매서드 레퍼런스가 너무 어렵다...

5, 6, 8, 9, 12

profile
갭린이 리나

0개의 댓글