[JAVA] 스트림 (Stream)

Teeput ㅣ 2024. 3. 27. 10:27

📚 들어가기


📌 File 클래스

Java에서 파일 시스템의 파일 및 디렉토리 경로를 나타내는 데 사용된다 이 클래스는 파일 및 디렉토리의 속성을 검사하고 조작할 수 있는 다양한 메서드를 제공한다

 

 

📌 File 클래스 써보기

package e01_file;

import java.io.File;
import java.util.Arrays;

public class FileTest {

	public static void main(String[] args) {
		// 파일 클래스 생성자에는 파일 전체 경로, 해당 폴더 경로를 문자열로 초기화
		File file = new File("c:\\Test\\p35.png ");

		System.out.println(file);
        
		// 현재 파일의 절대 경로 위치값을 뽑음
		System.out.println(file.getAbsolutePath());
		// 해당 파일이 저장된 폴더까지의 경로를 뽑음
		System.out.println(file.getParent());
		// 파일 클래스에 저장된 경로가 파일인지? 학인하는 메서드
		System.out.println(file.isFile());
		// 파일 클래스에 저장된 경로가 폴더인지? 확인하는 메서드
		System.out.println(file.isDirectory());
		// 파일 크키를 바이트 단위로 리턴하는 메서드
		System.out.println(file.length());
		// 현재 파일이 위치한 파티션의 총 크기
		System.out.println(file.getTotalSpace());
		// 현재 파일이 위치한 파티션이 사용가능한 용량 크기
		System.out.println(file.getUsableSpace());
		// 해당 경로, 또는 파일이 실제로 존재하는지 체크하는 메서드
		System.out.println(file.exists());
		// 파일명
		System.out.println(file.getName());
		// 현재 파일의 부모 폴더 경로를 파일 객체로 뽑음
		File parentPath = file.getParentFile();
		System.out.println(parentPath.getAbsolutePath());
		System.out.println(Arrays.toString(parentPath.list()));
	}

}

 

📌 데이터를 읽고 쓰는 데 사용되는 주요 클래스 및 인터페이스

FileReader
- 텍스트 파일을 읽는데 사용되는 클래스입니다
- 문자(char) 단위로 데이터를 읽습니다

FileWriter
- 텍스트 파일을 쓰는 데 사용되는 클래스입니다
- 문자(char) 단위로 데이터를 씁니다

DataRead
- 데이터를 읽는 데 사용되는 인터페이스 또는 클래스입니다
- 데이터 소스에서 바이트(byte) 또는 문자(String) 데이터를 읽습니다

DataWriter
- 데이터를 쓰는데 사용되는 인터페이스 또는 클래스입니다
- 데이터 소스로부터 바이트(byte) 또는 문자(String) 데이터를 씁니다

ObjectRead
- 객체로 읽는 데 사용되는 인터페이스 또는 클래스입니다
- 객체를 직렬화하여 데이터 스트림에서 읽습니다

ObjectWrite
- 객체를 쓰는 데 사용되는 클래스입니다
- 객체를 직렬화하여 데이터 스트림에 씁니다

PrintWrite
- 텍스트를 쓰는 데 사용되는 클래스입니다
- 다양한 형식의 데이터를 출력하기 위해 사용됩니다

InputStreamReader
- 바이트 입력 스트림을 문자 입력 스트림으로 변환하는 데 사용되는 클래스입니다
- 주로 파일이나 네트워크에서 바이트(byte)를 읽어 문자(String)로 변환합니다

OutputStreamReader
- 바이트 출력 스트림을 문자 출력 스트림으로 변환하는 데 사용되는 클래스입니다
- 주로 파일이나 네트워크에 바이트(byte) 데이터를 씁니다

 BufferedReader
-  버퍼링된 입력 문자 스트림을 읽는데 사용되는 클래스입니다
-  데이터를 읽을 때 입출력의 효율성을 높입니다

 

 

👨🏻‍💻 활용해보기


📌 File 클래스 활용하기

파일 생성

package e01_file;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class CreateFileTest {

	public static void main(String[] args) {
		File parenPath = new File("c:\\test");

		Scanner sc = new Scanner(System.in);
		System.out.print("파일명 입력하세요 : ");
		String fileName = sc.nextLine();

//		File newFile = new File(parenPath.getAbsolutePath() + "\\" + fileName);
		File newFile = new File(parenPath, fileName);
//		System.out.println(newFile.getAbsolutePath());
//		System.out.println(newFile.exists());

		try {
			// 파일 생성 작업
			// 1. 해당 폴더까지 경로가 있는지 체크
			if (!parenPath.exists()) {
				parenPath.mkdirs(); // 경로에 해당하는 모든 폴더를 없는 경우 생성
				System.out.println("해당 경로 생성 완료");
			}
			// 2. 파일 생성
			boolean result = newFile.createNewFile();
			if (result)
				System.out.println("파일 생성 성공");
			else
				System.out.println("파일 생성 실패");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

 

파일 삭제

package e01_file;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class DeleteFileTest {

	public static void main(String[] args) {
		File parenPath = new File("c:\\test");
		Scanner sc = new Scanner(System.in);

		System.out.println("=== 전체 파일 보기 ==");
		// 해당 폴더에 있는 모든 파일 목록을 출력
//		String[] fileList = parenPath.list();
		File[] fileList = parenPath.listFiles();
		List<File> list = Arrays.asList(fileList);
		list.forEach(item -> System.out.println(item.getName()));

		System.out.println("=== 파일 삭제를 시작합니다 ===");
		// 삭제할 파일명을 받아서 해당 파일을 삭제
		System.out.print("삭제할 파일명 입력 : ");
		String fileName = sc.nextLine();

		try {
            // 삭제할 파일 객체 생성
            File deleteFile = new File(parenPath, fileName);

            // 파일이 존재하는지 확인
            if (deleteFile.exists()) {
                // 파일 삭제
                boolean result = deleteFile.delete();
                if (result) {
                    System.out.println("파일 삭제 성공");
                } else {
                    System.out.println("파일 삭제 실패");
                }
            } else {
                System.out.println("삭제할 파일이 존재하지 않습니다");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

}

 

파일 수정

package e01_file;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class ReNameFileTest {

	public static void main(String[] args) {
		File parenPath = new File("c:\\test");
		Scanner sc = new Scanner(System.in);

		// 해당 폴더에 있는 모든 파일 목록을 출력
		List<File> list = Arrays.asList(parenPath.listFiles());
		list.forEach(item -> System.out.println(item.getName()));

		// 삭제할 파일명을 받아서 해당 파일을 변경
		System.out.println("변경할 기존 파일명 입력 : ");
		String fileName = sc.nextLine();
		System.out.println("변경할 새 파일명 입력 : ");
		String fileNewName = sc.nextLine();

		// 기존 파일에 연결
		File file = new File(parenPath, fileName);
		boolean result = file.renameTo(new File(parenPath, fileNewName));
		
		if (result)
			System.out.println("파일명 변경 완료");
		else
			System.out.println("파일명 변경 실패");
	}
}

 

FileReader

Try Catch 문 위에 초기화를 시킨 이유는 filnally에서 fr과 br을 닫을 때 try 지역변수로 설정 돼 있어서 닫을 수가 없으므로 try 지역변수 밖에서 초기화 시켰다
package e03_file_io;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderMain {

	public static void main(String[] args) {
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader("hello.txt");
			br = new BufferedReader(fr);

			while (true) {
				String str = br.readLine();
				if (str == null)
					break;
				System.out.println(str);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

 

FileWriter

package e03_file_io;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileWriterMain {

	public static void main(String[] args) {
		FileWriter fw = null;
		PrintWriter pw = null;
		try {
			// 1. node 스트림 생성 및 초기화
			fw = new FileWriter("hello.txt", true);

			// 2. process 스트림 생성 및 초기화
			pw = new PrintWriter(fw);

			// 3. 출력
			pw.println("Hello World");
			pw.println("안녕하세요?");
			pw.flush();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4. 닫기
			if (pw != null) {
				pw.close();
			}
		}

	}

}

 

DataWriter

try( 코드... ) 이렇게 넣으면 자동으로 close 되므로 닫는문장을 뺏다
package e03_file_io;

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataWriteTest {

	public static void main(String[] args) {
		try(FileOutputStream fos = new FileOutputStream("data.dat"); DataOutputStream dos = new DataOutputStream(fos);) {

			int n = 100;
			double pi = 3.1415;
			char ch = 'A';
			boolean flag = true;
			char c = '가';
			
			dos.writeInt(n);
			dos.writeDouble(pi);
			dos.writeChar(ch);
			dos.writeBoolean(flag);
			dos.writeChar(c);
			dos.flush();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}

 

DataRead

DataWrite는 입력된 순서대로 데이터 타입을 바이트로 전환 해 저장하므로 순서가 바뀌면 재대로 입력받지 못한다
package e03_file_io;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DataReadTest {

	public static void main(String[] args) {
		try(FileInputStream fis = new FileInputStream("data.dat"); DataInputStream dis = new DataInputStream(fis)) {
			int n = dis.readInt();
			double pi = dis.readDouble();
			char ch = dis.readChar();
			boolean flag = dis.readBoolean();
			char c = dis.readChar();
			
			System.out.println(n + " " + pi + " " + ch + " " + flag + " " + c);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

ObjectWrite

package e03_file_io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import javax.xml.stream.events.StartDocument;

public class ObjectWriteTest {

	public static void main(String[] args) {
		ArrayList<Person> list = new ArrayList<Person>();
		
		list.add(new Person("김씨", 20));
		list.add(new Person("이씨", 12));
		list.add(new Person("박씨", 24));
		list.add(new Person("곽씨", 34));
		list.add(new Person("장씨", 22));
		
		try(FileOutputStream fos = new FileOutputStream("person.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos)){
			
			for (int i = 0; i < list.size(); i++) {
				oos.writeObject(list.get(i));
			}
			oos.flush();
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static Object Start() {
		// TODO Auto-generated method stub
		return null;
	}

}

 

ObjectRead

package e03_file_io;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class ObjectReadTest {

	public static void main(String[] args) {
		ArrayList<Person> list = new ArrayList<Person>();
		
		try(FileInputStream fis = new FileInputStream("person.dat"); ObjectInputStream ois = new ObjectInputStream(fis);){
			
			// 파일에서 모든 객체를 받아와서 리스트에 저장
			try {
				while(true) {
					list.add((Person)ois.readObject());
				}
			} catch (EOFException e) {
				System.out.println("파일 읽기 완료");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("프로그램 종료");
	}

}

'Java' 카테고리의 다른 글

[JAVA] Oracle DB Java 연결하기  (0) 2024.04.16
[JAVA] 소켓 프로그래밍 (Socket)  (0) 2024.03.28
[JAVA] 싱글톤 패턴 (Singleton)  (0) 2024.03.26