[학습 목표]
1. Files.readAllLines(), write()를 이용해 파일 입출력 처리와 텍스트 파일 데이터 읽기/쓰기 기능을 구현한다. 2.Files.walk(), Files.list()를 활용해 디렉토리 탐색 및 파일 목록 처리 기능을 수행한다. 3. ByteBuffer, CharBuffer 등 다양한 Buffer 개념과 주요 메소드를 이해하고 직접 데이터 입출력을 구현할 수 있다.(put() , get() , flip(), clear() ) 4.Channel 과 Buffer 의 구조적 차이와 관계를 이해하고, NIO 기반 입출력 처리 패턴을 활용할 수 있다. 5. Path와 Paths 클래스 활용법을 이해하고, 파일 및 디렉토리 경로를 관리할 수 있다. |
Files.readAllLines(), write()를 이용해 파일 입출력 처리와 텍스트 파일 데이터 읽기/쓰기
byte 단위 입출력 | 문자열 단위 입출력 | Object 단위 입출력 |
Files.newOutputStream() Files.newInputStream() |
write() Files.readAllLines() - List<String> |
ObjectOutputStream() + Files.newOutputStream() ObjectInputStream() + Files.newInputStream() |
ex)
//1) byte 단위로 NIO
package com.sec13.myNio;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class g_NIOByte {
//-byte 단위 : Files.newOutputStream() , Files.newInputStream()
public static void main(String[] args) throws IOException {
Path path = Paths.get("a.txt");
//byte A ~ Z 까지 입출력하자.
//var 대신 BufferedOutputStream 으로 써도 된다. -> (BufferedOutputStream) Files.newOutputStream())
//var = 지역 변수 선언 , 컴파일시 타입이 결정난다. 람다식에는 사용할 수 없다.
//try(var out = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE) ) {
try(var out = Files.newOutputStream(path, StandardOpenOption.APPEND)){
for(byte i = 'A'; i <='Z';i++) {
out.write(i);
}
}
System.out.println("저장 완료!!");
System.out.println("데이터 결과 ");
try(var in = Files.newInputStream(path)){
int data = 0;
while((data = in.read())!= -1 ) {
System.out.print((char) data);
}
System.out.println();
}
}
}
//2) char 단위로 NIO
package com.sec13.myNio;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class h_NIOChar {
//문자열 단위 : write() , Files.readAllLines() - List<String>
public static void main(String[] args) throws IOException {
Path path = Paths.get("b.txt");
//문자열 쓰기
List<String> lines = List.of("public","static","void","main");
Files.write(path,lines);
System.out.println("저장 완료!!");
//문자열 읽기
List<String> lines02 = Files.readAllLines(path);
lines02.forEach(System.out::println);
}
}
//3) Object 단위로 NIO
package com.sec13.myNio;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
class Student implements Serializable {
private static final long serialVersionUID = 1L; // 직렬화 버전 관리
private String name;
private int age;
private int height;
private transient int weight; // transient 필드는 직렬화되지 않음
public Student() {}
public Student(String name, int age, int height, int weight) {
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
}
public String getName() { return name; }
public int getAge() { return age; }
public int getHeight() { return height; }
public int getWeight() { return weight; }
@Override
public String toString() {
return String.format("%10s %5d %5d %5d", name, age, height, weight);
}
}
public class h_MyObject2 {
public static void main(String[] args) {
String filename = "h.txt";
try {
MyWriter(filename);
MyReader(filename);
} catch (Exception e) {
System.out.println("예외 발생: " + e.getMessage());
}
}
private static void MyWriter(String filename) throws IOException {
Path path = Paths.get(filename);
try (ObjectOutputStream oo = new ObjectOutputStream(Files.newOutputStream(path, StandardOpenOption.CREATE))) {
oo.writeObject(new Student("111", 1, 1, 1));
oo.writeObject(new Student("222", 2, 2, 2));
oo.writeObject(new Student("333", 3, 3, 3));
System.out.println("파일에 객체를 저장했어");
}
}
private static void MyReader(String filename) throws IOException, ClassNotFoundException {
Path path = Paths.get(filename);
try (ObjectInputStream oi = new ObjectInputStream(Files.newInputStream(path))) {
while (true) {
try {
Student student = (Student) oi.readObject();
System.out.println(student);
} catch (Exception e) {
break; // 파일 끝 도달 (EOFException 발생 가능)
}
}
System.out.println("파일에서 객체를 성공적으로 읽었어!");
}
}
}
Files.walk(), Files.list()를 활용해 디렉토리 탐색 및 파일 목록 처리
https://docs.oracle.com/javase/8/docs/api/index.html
Java Platform SE 8
docs.oracle.com
static Stream<Path> walk(Path start, FileVisitOption... options) -> start 패스를 시작으로 디렉토리 탐색결과를 Stream<Path>로 리턴
static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options)
static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) -> start 패스를 시작으로 디렉토리 탐색 중에 발생되는 이벤트를 FileVisitor 처리 후 start 패스로 리턴
static Path walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor)
====> 1) 위 오버로드 메소드를 통해 디렉토리 순회결과 및 이벤트 확인 FileVisitor
2) FileVisitor 인터페이스를 사용한 커스텀 FileVisitor를 생성하는 방법
3) SimpleFileVisitor 클래스를 사용한 커스텀 이벤트 선택적으로 생성하는 방법
4) BasicFileAttributes 파일의 기본 속성값 활용하는 방법
다양한 Buffer 개념과 주요 메소드로 직접 데이터 입출력을 구현
allocate :초기 메모리 할당
put() : 데이터 저장
get() : 데이터 리턴
flip() : 읽기 전환 (position 0 , limit 는 마지막 데이터로 설정)
clear() : 버퍼 재사용준비 , (position 0 , limit 는 초기화)
package com.sec13.myNio;
import java.nio.ByteBuffer;
public class i_BufferedTest {
public static void main(String[] args) {
System.out.println("=====bytebuffer 확인========");
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
byteBuffer.put((byte)'A'); //position = 1
byteBuffer.put((byte)'B'); //position = 2
byteBuffer.put((byte)'C'); //position = 3
byteBuffer.put((byte)'D'); //position = 4
byteBuffer.mark(); //position = 4에 마킹 [0]A -> [1]B ->[2]C -> [3]D
byteBuffer.put((byte)'E'); //position = 5
byteBuffer.put((byte)'F'); //position = 6
byteBuffer.put((byte)'G'); //position = 7
System.out.println("데이터 저장 후 before reset " + byteBuffer.position() +" "+ byteBuffer.limit());
byteBuffer.reset(); // mark 위치로 돌아감 position = 2
byteBuffer.put((byte) 'F'); //덮어쓰기 C 덮어쓰기 E로 변경됨
//읽기
System.out.println("읽기");
byteBuffer.flip();
System.out.println("flip() 이후 데이터 저장 후 " + byteBuffer.position() +" "+ byteBuffer.limit());
while(byteBuffer.hasRemaining()) {
System.out.println(byteBuffer.get());
}
}
}
[실행 결과]
NIO 기반 입출력 처리 패턴을 활용
ex)
package com.sec13.myNio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
//nio -> buffer와 channel만 적절히 주면 된다.
public class b_nio {
public static void myread() {
try (FileChannel channel = FileChannel.open(Paths.get("a.txt"), StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(1024); //버퍼 크기 생성
while (channel.read(buffer) > 0) { //1024 데이터를 채널 (비동기 병렬할 대상인 a.txt)로 읽어들인다
buffer.flip(); //읽기 상태 전환
System.out.print(new String(buffer.array(), 0, buffer.limit()));
buffer.clear(); //초기화
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void mywrite(String content) {
try (FileChannel channel = FileChannel.open(Paths.get("./a.txt"), StandardOpenOption.CREATE , StandardOpenOption.WRITE)) {
ByteBuffer buffer = ByteBuffer.wrap(content.getBytes());
channel.write(buffer);
buffer = ByteBuffer.wrap(System.lineSeparator().getBytes());
channel.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("NIO Read:");
myread();
System.out.println("\nNIO Write:");
mywrite("Appended using NIO.");
myread();
}
}
'🦁멋쟁이 사자처럼 15기 > 3월달 수업 내용 정리' 카테고리의 다른 글
멋쟁이 사자처럼 17회차 ( 03 / 21 ) (0) | 2025.03.21 |
---|---|
멋쟁이 사자처럼 16회차 ( 03 / 20 ) (0) | 2025.03.20 |
멋쟁이 사자처럼 14회차 ( 03 / 18 ) (0) | 2025.03.18 |
멋쟁이 사자처럼 13회차 ( 03 / 17 ) (0) | 2025.03.17 |
멋쟁이 사자처럼 12회차 ( 03 / 14 ) (0) | 2025.03.14 |