기초 뽀개기 - 입출력&파일

Clean Code Big Poo·2025년 4월 20일
0
post-thumbnail

Overview

자바 무료강의 2시간 완성을 시청하고 간략히 정리

입력

프로그램으로 어떤 데이터를 가져오는 것을 의미

사용

Scanner sc = new Scanner(System.in); // 키보드 입력 받아옴

예제

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("정수 입력");

        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        System.out.println("입력값 : "+num);
    }
}
// 정수 입력
// 1
// 입력값 : 1

스캐너 사용 방법

기능설명예시
next문자열 입력(단어 단위)String word = sc.next();
nextInt정수 입력int i = sc.nextInt();
nextDouble실수 입력double d = sc.nextDouble();
nextLine문장 입력(줄 단위)String line = sc.nextLine();

출력

프로그램에서 결과를 출력하거나 저장

사용

System.out.print();
System.out.println();
System.out.printf(); // 정해진 포맷으로 출력

예제

String name = "철수";
int age = 20;

System.out.printf("이름 %s 나이 %d",name , age);

printf 사용 방법

기호설명예시결과
d정수System.out.printf("%d",1);1
f실수System.out.printf("%f",1.1);1.200000
s문자열System.out.printf("%s","철수");철수
n줄바꿈System.out.printf("%s%n","철수");철수

기타

기호설명예시결과
-왼쪽정렬System.out.printf("%-4d",1);1___
+부호 표시System.out.printf("%+4d",1);__+1
0빈공간 0 으로System.out.printf("%04d",1);0001
,세자리마다 콤마System.out.printf("%,d",1000);1,000
.소수점 자리System.out.printf("%.2f",1.234);1.23

파일

파일 또는 폴더를 생성, 삭제, 정보 조회 등이 가능

파일 생성 예제

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

public class Main {
    public static void main(String[] args){
        String fileName = "test.txt";
        File file =new File(fileName);

        try{
            file.createNewFile();
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
}

폴더 생성 예제

import java.io.File;

public class Main {
    public static void main(String[] args){
        String folderName = "test";
        File folder =new File(folderName);

        try{
            folder.mkdir();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

기능 정리

기능설명예시
createNewFile새 파일 생성file.createNewFile()
exists파일 또는 폴더 존재 여부if(file.exists())
getName이름 정보file.getName()
getAbsolutePath정대 경로 정보file.getAbsolutePath();
length파일 크기(Byte)file.length()
mkdir폴더 만들기file.mkdir()
mkdirs폴더들 만들기file.mkdirs()
listFiles파일 및 폴더 목록 조회for(File file:file.listFiles())
isFile파일인지 여부if(file.isFile())
isDirectory폴더인지 여부if(file.isDirectory())
delete파일 또는 폴더 삭제file.delete()

파일 읽고 쓰기 예제

public class Main {
    public static void main(String[] args){
    	// 파일에 쓰기
        try(BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))){
        	// try-with-resource
            bw.write("감사합니다.");
            bw.newLine();
            bw.write("안녕히가세요.");
        }catch (IOException e){
            throw new RuntimeException(e);
        }

		// 파일 읽기
        try(BufferedReader br = new BufferedReader(new FileReader("test.txt"))){
        	// try-with-resource
            String line;

            while ((line = br.readLine()) != null){
                System.out.println(line);
            }

        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
}

0개의 댓글