-
[TIL] 2022년 9월 18일 일요일카테고리 없음 2022. 9. 18. 11:50
2.3 FileInputStream과 FileOutputStream
생성자 설명 FileInputStream(String name) Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. FileInputStream(File file) Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. FileInputStream(FileDescriptor fdObj) Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system. FileOutputStream(String name) Creates a file output stream to write to the file with the specified name. FileOutputStream(String name, boolean append) Creates a file output stream to write to the file with the specified name. append가 true이면 기존 파일 내용의 마지막에 덧붙이기, false이면 기존 파일 내용에 덮어쓰기 FileOutputStream(File file) Creates a file output stream to write to the file represented by the specified File object. FileOutputStream(File file, boolean append) Creates a file output stream to write to the file represented by the specified File object. append가 true이면 기존 파일 내용의 마지막에 덧붙이기, false이면 기존 파일 내용에 덮어쓰기 FileOutputStream(FileDescriptor fdObj) Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system. File Descriptor는 Unix나 Unix 운영체제에서 파일이나 파이프나 네트워크 소켓과 같은 다른 입출력 자원을 다루는 특별한 구분자이다. File Descriptor는 주로 양의 정수로 음수이면 에러이거나 값이 없는 것이다. PCB에 File Descriptor번호가 등록되면 파일 이름으로 FileInputStream과 FileOutputStream을 생성하듯 File Descriptor번호로 FileInputStream과 FileOutputStream을 생성할 수 있다.
import java.io.FileInputStream; import java.io.IOException; public class FileViewer { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream(args[0]); int data = 0; while ((data=fis.read()) != -1){ char c = (char)data; System.out.print(c); } } }
javac FileViewer.java ; FileViewer.java 컴파일
java FileViewer.java; FileViewer.java를 실행했으나 이 프로그램은 실행할 때 명령어 다음 인자를 매개변수로 받기때문에 이렇게만 입력하면 입력값이 없어 ArrayIndexOutOfBoundsException이 발생
java FileViewer FileViewer.java; 코드를 출력
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileCopy { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream(args[0]); FileOutputStream fos = new FileOutputStream(args[1]); int data = 0; while ((data = fis.read()) != -1){ fos.write(data); } fis.close(); fos.close(); }catch (IOException e){ e.printStackTrace(); } } }
FileCopy파일을 컴파일한 후 java FileCopy.java FileCopy.java FileCopy.bak 이 명령어를 수행했더니 FileCopy.bak로 파일을 복사했다.