logo

FileOutputStream 클래스는 바이트 스트림에 속하며 데이터를 개별 바이트 형태로 저장합니다. 텍스트 파일을 만드는 데 사용할 수 있습니다. 파일은 하드 디스크나 CD와 같은 보조 저장 매체에 데이터를 저장하는 것을 나타냅니다. 파일을 사용할 수 있는지 또는 생성할 수 있는지 여부는 기본 플랫폼에 따라 다릅니다. 특히 일부 플랫폼에서는 한 번에 하나의 FileOutputStream(또는 기타 파일 쓰기 개체)만 쓰기 위해 파일을 열 수 있습니다. 이러한 상황에서 관련 파일이 이미 열려 있으면 이 클래스의 생성자가 실패합니다. FileOutputStream은 이미지 데이터와 같은 원시 바이트 스트림을 쓰기 위한 것입니다. 문자 스트림을 작성하려면 FileWriter를 사용하는 것이 좋습니다. 중요한 방법:
    무효 닫기() :  파일에 대한 연결을 정리하고 이 스트림에 대한 참조가 더 이상 없을 때 이 파일 출력 스트림의 닫기 메서드가 호출되도록 합니다. 무효 쓰기(바이트[] b) :  void write(byte[] b int off int len) : 오프셋 off에서 시작하여 지정된 바이트 배열의 len 바이트를 이 파일 출력 스트림에 씁니다. 무효 쓰기(int b) : 
    데이터 읽기: First of all data should be read from the keyboard. For this purpose associate the keyboard to some input stream class. The code for using DataInputSream class for reading data from the keyboard is as:
    DataInputStream dis =new DataInputStream(System.in);
    Here System.in represent the keyboard which is linked with DataInputStream object Now associate a file where the data is to be stored to some output stream. For this take the help of FileOutputStream which can send data to the file. Attaching the file.txt to FileOutputStream can be done as:
    FileOutputStream fout=new FileOutputStream(file.txt);
    The next step is to read data from DataInputStream and write it into FileOutputStream . It means read data from dis object and write it into fout object as shown here:
    ch=(char)dis.read(); fout.write(ch);
    파일을 닫습니다.마지막으로 파일에 대한 입력 또는 출력 작업을 수행한 후에는 모든 파일을 닫아야 합니다. 그렇지 않으면 해당 파일의 데이터가 손상될 수 있습니다. 파일 닫기는 연관된 스트림을 닫음으로써 수행됩니다. 예를 들어 fout.close():는 FileOutputStream을 닫으므로 파일에 데이터를 쓸 수 있는 방법이 없습니다.
구현: Java
//Java program to demonstrate creating a text file using FileOutputStream import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; class Create_File {  public static void main(String[] args) throws IOException   {  //attach keyboard to DataInputStream  DataInputStream dis=new DataInputStream(System.in);  // attach file to FileOutputStream  FileOutputStream fout=new FileOutputStream('file.txt');  //attach FileOutputStream to BufferedOutputStream  BufferedOutputStream bout=new BufferedOutputStream(fout1024);  System.out.println('Enter text (@ at the end):');  char ch;  //read characters from dis into ch. Then write them into bout.  //repeat this as long as the read character is not @  while((ch=(char)dis.read())!='@')  {  bout.write(ch);  }  //close the file  bout.close();  } } 
If the Program is executed again the old data of file.txt will be lost and any recent data is only stored in the file. If we don’t want to lose the previous data of the file and just append the new data to the end of already existing data and this can be done by writing true along with file name.
FileOutputStream fout=new FileOutputStream(file.txttrue); 

BufferedOutputStream을 사용하여 효율성 향상

Normally whenever we write data to a file using FileOutputStream as:
fout.write(ch);
Here the FileOutputStream is invoked to write the characters into the file. Let us estimate the time it takes to read 100 characters from the keyboard and write all of them into a file.
  • DataInputStream을 사용하여 키보드에서 메모리로 데이터를 읽고 문자 1개를 메모리로 읽는 데 1초가 걸리며 이 문자는 FileOutputStream에 의해 파일에 1초 더 소비되어 기록된다고 가정해 보겠습니다.
  • So for reading and writing a file will take 200 sec. This is wasting a lot of time. 반면에 Buffered 클래스가 사용되는 경우 파일에 즉시 쓸 수 있는 버퍼의 문자로 먼저 채워지는 버퍼를 제공합니다. Buffered classes should be used in connection to other stream classes.
  • First the DataInputStream reads data from the keyboard by spending 1 sec for each character. This character is written into the buffer. Thus to read 100 characters into a buffer it will take 100 second time. Now FileOutputStream will write the entire buffer in a single step. So reading and writing 100 characters took 101 sec only. In the same way reading classes are used for improving the speed of reading operation.  Attaching FileOutputStream to BufferedOutputStream as:
    BufferedOutputStream bout=new BufferedOutputStream(fout1024);
    Here the buffer size is declared as 1024 bytes. If the buffer size is not specified then a default size of 512 bytes is used
    무효 플러시() :  void write(byte[] b int off int len) : 오프셋 off에서 시작하여 지정된 바이트 배열의 len 바이트를 이 버퍼링된 출력 스트림에 씁니다. 무효 쓰기(int b) : 
산출:
C:> javac Create_File.java C:> java Create_File Enter text (@ at the end): This is a program to create a file @ C:/> type file.txt This is a program to create a file 
  • Java의 파일 클래스
  • FileWriter 및 FileReader를 사용하여 Java에서 파일 처리
퀴즈 만들기