Input과 Output의 약자, 컴퓨터 내부 또는 외부 장치와 프로그램 간의 데이터를 주고 받는 것
stream:
입출력 장치에서 데이터를 읽고 쓰기 위해서 자바에서 제공하는 클래스,
하나의 스트림으로 입출력을 동시에 수행할 수 없으므로 동시에 수행하려면 2개의 스트림 필요
File클래스
파일시스템의 파일을 표현하는 클래스
파일크기 , 파일속성 , 파일이름등의 정보와 파일 생성및 삭제기능 제공
import java.io.File;
import java.io.IOException;
public class TestFile {
public static void main(String[] args) {
// File 클래스 테스트
File file = new File("person.txt");
System.out.println("파일명 : "+file.getName()); //파일명을 찾음
System.out.println("저장 경로 : " + file.getAbsolutePath());//절대적인 경로 찾음
System.out.println("저장 경로 : " + file.getPath()); //그냥 경로
System.out.println("파일 크기 : " + file.length());//파일크기
try {
//파일이 없는경우에는 파일 생성하고 true값 리턴.
//기존에 파일이 존재하면 false 리턴해줌 -> 다시 실행하니 false값이 나옴(이미파일이 만들어졌기때문)
boolean b = file.createNewFile();
//파일 만들기 -> 그냥만들면 에러떠서 트라이캐치 사용
System.out.println(b);
} catch (IOException e) {
e.printStackTrace();
}
}
}출력값:
파일명 : person.txt
저장 경로 : /Users/ro_doll99/1_java/Java16_IO/person.txt
저장 경로 : person.txt
파일 크기 : 6
false
다른예제
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestByteStream {
public void fileSave() {
FileOutputStream fout = null;
try { // 언핸들드 익셉션 -> 예외처리 하세요! -> 트라이캐치 사용
fout = new FileOutputStream("sample.txt"); // 어디에 연결할건지?
fout.write(97); // 내보내야함 -> write
byte[] bar = { 98, 99, 100, 101, 102, 10 }; // byte 배열 생성
fout.write(bar); // byte배열을한번에
// bar 배열을내보내니 txt.sample에 abcdef 출력
// 10 은 줄바꿈
fout.write(bar, 1, 3); // cde만저장됨 bar배열의 index 1부터3까지 저장함
} catch (FileNotFoundException e) {
e.printStackTrace(); // 1.트라이캐치문 사용
} catch (IOException e) {
e.printStackTrace(); // 2.트라이캐치문 재사용
} finally {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} // 출력 해내기
public void fileOpen() {
FileInputStream fin = null;
try {
fin = new FileInputStream("sample.txt");// 누구랑 연결을 할거냐? ("얘랑")
int fileSize = (int) new File("sample.txt").length(); // int타입만 가능해서int로 형변환
byte bar[] = new byte[fileSize]; // 바이트배열 생성
fin.read(bar); /* 읽어오자 (바이트배열에 담아서 ) */
for(int i = 0 ; i <bar.length; i ++) {
System.out.print((char)bar[i]+ " "); // 유티코드 값 그대로 출력됨 ,
//char 이용해서 문자(캐릭터)로 변경
//byte 배열 사용하지않고 하나씩 읽어오기
int val;
while((val=fin.read())!= -1 ) {
System.out.print((char) val + " ");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} // 받아오기
출력값:
a b c d e f
c d e
↓ ユ ネ → ナ ユ ■ ユ リ ↓ ト ᄌ ↓ レ ヤ
'JAVA' 카테고리의 다른 글
[JAVA] Collection(List , set , Map) (1) | 2024.02.27 |
---|---|
[JAVA]입출력( I / O ) #2 (1) | 2024.02.26 |
[JAVA]예외처리 (0) | 2024.02.22 |
[JAVA]객체#3 (0) | 2024.02.21 |
[JAVA]객체#2 (0) | 2024.02.20 |