⚡ Files(nio 형태) 이용한 파일 내용을 배열에 저장
File : io / Files : nio(Buffer 장착) => (https://dev-eunse.tistory.com/3) 참고
io,nio 둘중 하나만 사용 ! - 알아서 선택
Files : new 작성할필요 x - 어차피 메모리에 저장되기때문에
- nio 방식
public static void main(String[] args) {
String url = "D:\\webpage\\agree\\src\\main\\java\\io\\agree.txt";
try {
//List interface 구성 형태로 nio 배열 저장
List<String> data = new ArrayList<String>(); //List로만 사용 가능
data = Files.readAllLines(Paths.get(url)); //new 사용x 바로 data에 넣음
//ArrayList Class 구성형태를 사용할 경우엔 이렇게 작성,위와 동일하게 출력
//data.addAll(Files.readAllLines(Paths.get(url)));
//[회원가입 약관, 2024년 5월 약관개정, 부칙, 본 내용은 2024년 5월부로]
//이렇게 한줄씩 배열에 담겨 출력
System.out.println(data);
}catch(Exception e) {
System.out.println(e.getMessage());
}
}
▼ io 방식으로 동일하게 출력한다면? - 반복문 사용
FileReader fr = new FileReader(url);
BufferedReader br = new BufferedReader(fr);
ArrayList<String> data = new ArrayList<String>(); //List,ArrayList.. 등 아무거나 사용 무관
String msg = "";
while((msg = br.readLine()) != null){
data.add(msg);
}
System.out.println(data);
br.close();
fr.close();
▼byte + nio를 활용 / 참고 : https://dev-eunse.tistory.com/82
byte data[] = Files.readAllBytes(Paths.get(url));
String unbox = new String(data);
System.out.println(unbox); // 각 한줄씩 반복문 돌린것처럼 출력됨
⚡ Files(nio)를 이용한 .txt파일에 데이터 저장 - .write()
io라면 FileWriter 사용
숫자 형태는 저장 불가
nio의 write : write(경로,문자열.getBytes(),언어셋) (언어셋 생략가능)
public static void main(String[] args) throws Exception{
String url = "D:\\webpage\\agree\\src\\main\\java\\io\\member.txt";
String msg = "이순신";
Path path = Paths.get(url); //Path라는 인터페이스 사용 , nio 경로
Files.write(path, msg.getBytes(),StandardOpenOption.APPEND);
//close 필요 없음 , byte단위 사용 , 숫자는 불가
/*
*** StandardOpenOption : 파일형태 삭제,추가,생성 여부
-StandardOpenOption.APPEND : 기존 데이터 보존,새로운 값을 추가(미작성시 무조건 덮어씌어 저장됨)
-StandardOpenOption.WRITE : 기존 데이터 덮어쓰기
-StandardOpenOption.CREATE :해당 경로에 동일 파일명이 없을 경우 생성 후 데이터 추가
-StandardOpenOption.CREATE_NEW : 새로운 파일을 생성하여 데이터를 추가
-StandardOpenOption.DELETE_ON_CLOSE : 파일 삭제
-StandardOpenOption 미사용 : 기존 데이터 삭제 후 새로운 데이터 추가
*/
}
⚡ Files(nio)를 이용한 파일복사
RandomAccessFile : 해당 파일 권한에 맞춰서 쓰기,읽기 설정하는 클래스
FileChannel : nio클래스(파일 읽기,쓰기,맵핑)
transferTo : 데이터 0btyte ~ 크기만큼 내용 복사
public static void main(String[] args) throws Exception {
String url = "D:\\webpage\\agree\\src\\main\\java\\io\\agree.txt";
String url2 = "D:\\webpage\\agree\\src\\main\\java\\io\\agree2.txt";
//--io+nio 로 복사
File f1 = new File(url); //오리지널 파일
File f2 = new File(url2); //복사할 파일
Files.copy(f1.toPath(), f2.toPath(), StandardCopyOption.REPLACE_EXISTING);
//--io+nio 복사2 (rwx r:읽기전용 , w:쓰기, x : 실행 )
RandomAccessFile f3 = new RandomAccessFile(url, "r");
RandomAccessFile f4 = new RandomAccessFile(url2, "rw"); //읽으면서 써야하니까
FileChannel fc = f3.getChannel();
System.out.println(fc.size()); //원본파일 용량확인
FileChannel fc2 = f4.getChannel();
//fc.transferTo(0, 20, fc2); //맨 위 첫째줄만 복사해서 파일 생성됨
fc.transferTo(0, fc.size(), fc2); //파일 데이터 모두 복사해서 파일 생성됨
}
⚡ Files JAVA11 ver
( 위 예제는 JAVA 예전버전 이었음..)
public static void main(String[] args) {
try {
//createDirectories : 디렉토리를 생성
Files.createDirectories(Paths.get("d:\\images"));
/*--파일복사 : Path(interface) copy로 복사
Path data1 = Paths.get("D:\\images\\gugu.txt");
Path data2 = Paths.get("D:\\images\\gugu2.txt");
Files.copy(data1, data2);
*/
/*--파일을 다른 곳으로 이동
Path data3 = Paths.get("D:\\images\\gugu2.txt");
Path data4 = Paths.get("D:\\gugu2.txt");
Files.move(data3, data4);*/
/*--파일 생성하는 방식
Path data5 = Paths.get("D:\\images\\gugu_copy.txt");
Files.createFile(data5);*/
//--파일 삭제
Path data6 = Paths.get("D:\\images\\gugu_copy.txt");
Files.delete(data6);
}catch(Exception e) {
System.out.println(e.getMessage());
}
}