java,jsp,spring/java
java 입,출력 스트림
프루트
2022. 8. 6. 09:06
입력 스트림, 출력 스트림
- 개념
- 바이트 기반 스트림, 문자 기반 스트림
- 바이트 : 그림, 멀티미디어, 문자 포함
- 문자
- 차이점 : 바이트 기반 > int 타입 / 문자 기반 > char 타입
- 입력 스트림
- int read() : 한 바이트를 읽어 들인다. 단, 더이상 읽어올 자료가 없으면 -1을 반환
- int read(byte b[]) : 바이트 배열을 읽어 들임
- int read(byte b[], int off, int len) : 바이트 배열의 주어진 위치에 주어진 길이 만큼 읽어 들임
[예시 코드]
import java.io.FileInputStream;
import java.io.InputStream;
public class ReadExample2 {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream("d:/test.txt");
int readByteNo;
byte[] readBytes = new byte[3];
String data = "";
// 방법 1
while (true) {
readByteNo = is.read(readBytes);
// System.out.print((char)readByteNo); -- 글자가 깨져서 출력
if (readByteNo == -1) {
break;
}
data += new String(readBytes, 0, readByteNo);
}
//방법 2
while ((readByteNo=is.read(readBytes))!=-1) {
data += new String(readBytes, 0, readByteNo);
}
System.out.println(data);
is.close();
}
}
- 출력 스트림
- void close() : 스트림을 닫는다. 스트림을 사용해서 모든 작업을 마치고 난 후에는 close()를 호출해서 반드시 닫아주어야 한다. (메모리를 사용하는 스트림과 표준 입출력 스트림은 닫아 주지 않아도 된다.)
- void flush() : 출력 스트림이 갖고 있는 버퍼의 내용을 모두 출력 스트림으로 내보내고 비운다. *버퍼가 있는 출력 스트림의 경우에만 의미가 있다.
- int write(byte[] b, int off, int len) : b 배열의 off위치부터 len 만큼 출력한다.
- void write(byte[] b) : 바이트 배열로 출력한다.
- void write(int b) : 한 바이트로 출력한다.
[예시 코드]
import java.io.FileOutputStream;
import java.io.OutputStream;
public class WriteExample1 {
public static void main(String[] args) throws Exception {
OutputStream os = new FileOutputStream("d:/output.txt");
byte[] data = "ABC".getBytes();
// 방법 1
for (int i = 0; i < data.length; i++) {
os.write(data[i]);
} // d드라이브에 output.txt가 만들어지고 내용은 ABC가 입력되어 있음
// 반복문이기 때문에 배열 하나씩 출력
// 방법 2
os.write(data);
// 한번에 출력
// 방법 3
os.write(data, 1, 2);
// 인덱스 1에서 2까지 출력
os.flush();
os.close();
}
}
파일 입출력
- File 클래스
- 파일을 표현
- 크기, 속성, 이름 등의 정보 제공
- 생성 및 삭제 기능
- 디렉토리 생성, 파일 리스트 얻어내는 기능
- 객체 생성
- 파일을 표현
File file = new File("C:\\Temp\\file.txt"); File file = new File("C:/Temp/file.txt");
-
- 파일 또는 디렉토리 존재 유무
bollean isExist = file.exists();
-
- 생성 및 삭제
리턴타입 메소드 의미 boolean createNewFile() 파일을 만듬 boolean mkdir() / mkdirs() 폴더를 만듬 // 폴더 여러개를 만듬 boolean delete() 삭제 boolean canExecute() 실행 가능 파일인지 여부 canRead() 읽기 가능한지 여부 리턴 canWrite() 쓰기 가능한지 여부 리턴 String getName() 이름을 반환 getParent() 부모 디렉토리 리턴 getPath() 파일의 전체 경로를 반환 File getParentFile() 부모 디렉토리를 File 객체로 생성 후 리턴 boolean isDirectory() 폴더인지 여부 리턴 isFile() 파일인지 여부 리턴 isHidden() 숨겨져 있는지 여부 리턴 long lastModified() 최근 수정 날짜 length() 파일의 크기 String[] list() 디렉토리에 포함된 파일 및 서브 디렉토리 목록 전부를 String 배열로 리턴 file[] listFiles() 디렉토리에 포함된 파일 및 서브 디렉토리 목록 전부를 File 배열로 리턴
- 생성 및 삭제
[예시 코드]
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileExample {
public static void main(String[] args) throws Exception {
// File dir = new File("d:/test");
// dir.mkdir(); 폴더 1개만 생성
File dir = new File("d:/test/dir");
dir.mkdirs(); //경로의 폴더 다 생성
File file1 = new File("d:/test/file1.txt");
File file2 = new File("d:/test/file2.txt");
File file3 = new File("d:/test/file3.txt");
file1.createNewFile();
file2.createNewFile();
file3.createNewFile();
// 이미 존재하거나, 권한 부족 등의 이유로 생성 못할 경우를 위한 예외 처리 필요
File test = new File("d:/test");
File[] contents = test.listFiles();
System.out.println("날짜 시간 형태 크기 이름");
System.out.println("-------------------------------------------");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd a hh:mm");
for (int i = 0; i < contents.length; i++) {
System.out.print(sdf.format(new Date(contents[i].lastModified())));
if (contents[i].isDirectory()) {
System.out.println("\t<DIR>\t\t"+contents[i].getName());
} else {
System.out.println("\t\t"+contents[i].length()+"\t"+contents[i].getName());
}
}
//lastModified() : 1970년도 부터 밀리초 단위로 최근 수정 날짜 표시
//Date() : 날짜 형식으로 표시
//SimpleDateFormat() : 간단한 날짜형식으로 표시
}
}