개인개발기록/클라우드 기반 자바 풀스택 개발

2025_04_08 Java 풀스택 수업

pop2bubbledev 2025. 4. 8. 17:53

데이터 입출력 :

데이터는 키보드를 통해 입력될 수도 있고 파일 또는 프로그램으로부터 입력될수있다

또한 반대로 데이터는 모니터로 출력 될 수도 있고 파일에 저장되거나 다른 프로그램으로 전송될 수 있다

 

Java 는 입력 스트림과 출력 스트림을 통해 데이터를 입출력함

 

                     ** 스트림은 반대로 향하지 못한다 **

 

             입력 스트림                             출력 스트림

입력             ->                프로그램              ->              도착지

 

입력 스트림 :

키보드 / 파일 / 프로그램 등으로 부터 들어오는 자료

출력 스트림 :

프로그램에서 파일 / 모니터 / 프로그램으로 데이터를 보내는것

 

바이트 스트림 과 문자스트림

바이트 스트림 :

바이트(Byte) 단위로 데이터를 입/출력한다. 그림 멀티미디어 등의 바이너리 데이터를 읽고 출력할때 사용

 

문자 스트림 :

문자단위로 입/출력 한다 주로 채팅프로그램등에 사용

 

read() 메소드 :

입력 스트림으로부터 1byte를 읽고 int(4byte) 타입으로 리턴한다 따라서 4byte 중 마지막 1byte 에만 데이터가 들어가있다

만약 더이상 바이트를 읽을 수 없다면 -1 을 리턴하는데 이것을 이용하여 마지막 바이트까지 읽을수있다

public class ReadMain02 {
    public static void main(String[] args) {
        try (InputStream is = new FileInputStream("data/test1.txt");){

            byte[] data = new byte[100];
            int readData;

            //is.read(data) : 최대 100byte 를 읽어서 data[]에 저장
            //읽은 바이트는 리턴
            //readData : 실제로 읽은 바이트 수
            while((readData = is.read(data)) != -1){
                for(int i=0; i<readData; i++){
                    System.out.println((char)data[i]);
                }
            }

        } catch (IOException e){
            e.printStackTrace();
        }
    }
}

 

 

보조 스트림 :

다른 스트림들과 연결되어 편리한 기능을 제공한다

보조 스트림은 자체적으로 입출력할수 없어 InputStream , OutputStream , Reader , Writer 등이 필요하다

연결 제한은 없어 보조스트림 여러개를 붙일수도있다

 

보조스트림 변수 = new 보조스트림(입출력 스트림);

Ex)

InputStream input = new FileInputStream("....");
InputStreamReader reader = new InputStreamReader( is );
BufferedReader br = new BufferdReader( reader );

 

InputStreamReader 바이트 스트림 => 문자 스트림

 

//InputStream || OutputStream || Reader || Writer 가 뒤에 붙는다는 가정하에 작성한다

Buffered *              //입출력 성능 향상

 

Data input || output                  //기본타입 데이터 입출력

 

PrintStream, PrintWriter          //줄바꿈 처리 및 형식화된 문자열 출력

 

Object input || output              //객체 입출력

 

문자 변환 스트림

바이트 스트림에서 입출력할 데이터가 문자라면 문자 스트림(Reader 와 Writer)로 변환해서 사요하면 좋다.

 

 

File 과 Files 클래스

파일이나 폴더를 생성 && 삭제 정보 확인가능

Files 클래스는 File 클래스를 개선한 클래스로 더욱 많은 기능을 가지고있다

 

File 클래스 :

File file = new File("경로")

지정을 해줘야 그 파일을 기반으로 사용가능

 

※ ※  File 객체를 생성했다고 해서 파일이나 디렉토리가 생성되는 것은 아니다 ※ ※

파일이나 디렉토리가 실제 있는지 확인하고 싶다면 File 객체를 생성하고 나서 exists() 메서드를 호출해 확인한다

 

File file = new File("....")

boolean is Exist = file.exists()    실제 파일이 있다면 true 없다면 flase

package Day20.IO.FileExam;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class FileMain {
    public static void main(String[] args) throws IOException {

        // 객체 생성
        File dir = new File("data/examdir");
        File dir2 = new File("c:/temp");

        File file = new File("data/examdir/test1.txt");
        File file2 = new File("c:/temp/test2.txt");

        //1. exists() : 파일 또는 디렉토리의 존재 여부 확인
        //     존재하면 true, 존재하지 않으면 false
        System.out.println("Directory exists: " + dir.exists());
        System.out.println("Directory2 exists: " + dir2.exists());

        System.out.println("File exists : " + file.exists());
        System.out.println("File2 exists : " + file2.exists());

        //2. mkdir() : 디렉토리 생성
        boolean createDir = dir.mkdir();
        System.out.println("Directory created : " + createDir);
        boolean createDir2 = dir.mkdir();
        System.out.println("Directory2 created : " + createDir2);

        //3. createNewFile() : 새 파일 생성
        boolean createFile = file.createNewFile();
        System.out.println("File create : " + createFile);
        boolean createFile2 = file2.createNewFile();
        System.out.println("File create : " + createFile2);

//        //4. delete() : 파일 또는 디렉토리를 삭제
//        System.out.println("File deleted : " + file.delete());
//        System.out.println("Directory deleted : " + dir.delete());

        //5. isFile() : 파일인지 확인
        System.out.println("Is file exists : " + file.isFile());
        System.out.println("Is file2 exists : " + file2.isFile());

        //8. isDirectory() : 디렉토리인지 확인
        System.out.println("Is directory exists : " + dir.isDirectory());
        System.out.println("Is directory2 exists : " + dir2.isDirectory());

        //7. getName() : 파일 또는 디렉토리의 이름을 반환
        System.out.println("File name : " + file.getName());
        System.out.println("File2 name : " + file2.getName());
        System.out.println("Directory name : " + dir.getName());
        System.out.println("Directory2 name : " + dir2.getName());

        //8. getPath() : 전체 경로를 리턴
        System.out.println("File path : " + file.getPath());
        System.out.println("File2 path : " + file2.getPath());
        System.out.println("Directory path : " + dir.getPath());
        System.out.println("Directory2 path : " + dir2.getPath());

        //9. getAbsolutePath() : 절대 경로를 리턴
        System.out.println("File Absolute path : " + file.getAbsolutePath());
        System.out.println("File2 Absolute path : " + file2.getAbsolutePath());
        System.out.println("Directory Absolute path : " + dir.getAbsolutePath());
        System.out.println("Directory2 Absolute path : " + dir2.getAbsolutePath());

        //10. 정규화된 경로 파악 : 디렉토리부터 시작하여 경로를 알려준다
        System.out.println("File 정규화 경로 : " + file.getCanonicalPath());
        System.out.println("File2 정규화 경로 : " + file2.getCanonicalPath());
        System.out.println("Directory 정규화 경로 : " + dir.getCanonicalPath());
        System.out.println("Directory2 정규화 경로 : " + dir2.getCanonicalPath());

        File dir3 = new File("/examdir/..");
        File dir4 = new File("../examdir");

        System.out.println("Directory3 정규화 경로 : " + dir3.getCanonicalPath());
        System.out.println("Directory4 정규화 경로 : " + dir4.getCanonicalPath());

        //11. length() : 파일의 크기를 바이트 단위로 반환
        System.out.println("File size : " + file.length());
        System.out.println("File2 size : " + file2.length());
        System.out.println("Directory size: " + dir.length());
        System.out.println("Directory2 size: " + dir2.length());

        //12. lastModified() : 마지막으로 수정된 시간
        System.out.println("File modified : " + file.lastModified());
        System.out.println("File2 modified : " + file2.lastModified());
        System.out.println("Directory modified : " + dir.lastModified());
        System.out.println("Directory2 modified : " + dir2.lastModified());

        //13. renameTo() : 파일의 이름 변경 또는 이동


    }
}

 

Files 클래스 :

Files 클래스는 Static 메서드로 구성되어 있다

File 클래스처럼 객체 생성을 할 필요가 없다

Fles의 정적 메서드는 운영체제의 파일 시스템에게 파일 작업을 수행하도록 위임한다.

package Day20.IO.FileExam;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FilesMain {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("data/examdir/hello.txt");
        Path directory = Path.of("data/examdir");

        //1. exists() : 파일이나 디렉토리의 존재 여부 확인
        System.out.println("File exists : " + Files.exists(file));
        System.out.println("Directory exists : " + Files.exists(directory));

        //2. createFile() : 새 파일 생성
        try {
            Files.createFile(file);
            System.out.println("File created : " + Files.exists(file));
            Files.createDirectories(directory);
            System.out.println("Directory created : " + Files.exists(directory));

        } catch (FileAlreadyExistsException e) {
            System.out.println(file + " || " + directory + " : 가 이미 존재합니다");
        }
        
        
        //3. delete() : 파일이나 디렉토리 삭제
        try {
            Files.delete(file);
            Files.delete(directory);
            System.out.println("Files deleted : " + Files.exists(file));
            System.out.println("Directory deleted : " + Files.exists(directory));
        } catch (DirectoryNotEmptyException e){
            System.out.println("디렉토리가 비어있지 않습니다.");
        }






    }
}