logo

Vytvorenie súboru pomocou FileOutputStream

Trieda FileOutputStream patrí do bajtového toku a ukladá dáta vo forme jednotlivých bajtov. Môže sa použiť na vytváranie textových súborov. Súbor predstavuje uloženie údajov na druhom pamäťovom médiu, ako je pevný disk alebo CD. To, či je súbor dostupný alebo môže byť vytvorený, závisí od základnej platformy. Najmä niektoré platformy umožňujú naraz otvárať súbor na zápis iba jedným FileOutputStream (alebo inými objektmi na zapisovanie súborov). V takýchto situáciách konštruktory v tejto triede zlyhajú, ak je príslušný súbor už otvorený. FileOutputStream je určený na písanie tokov nespracovaných bajtov, ako sú napríklad obrazové údaje. Na písanie prúdov znakov zvážte použitie FileWriter. Dôležité metódy:
    void close() : Zatvorí tento výstupný prúd súboru a uvoľní všetky systémové prostriedky spojené s týmto prúdom. protected void finalize() : Vyčistí pripojenie k súboru a zabezpečí, aby sa zavolala metóda zatvorenia tohto výstupného toku súboru, keď už neexistujú žiadne odkazy na tento tok. void write(byte[] b): Zapíše b.length bajty zo zadaného bajtového poľa do tohto výstupného toku súboru. void write(byte[] b int off int len) : Zapíše len bajty zo zadaného bajtového poľa počnúc offsetom do tohto výstupného toku súboru. void write (int b): Zapíše zadaný bajt do tohto výstupného toku súboru.
Ak chcete vytvoriť textový súbor, v ktorom budú uložené niektoré znaky (alebo text), postupujte podľa nasledujúcich krokov:
    Čítanie údajov: 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 Odoslať údaje do OutputStream: 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);
    Čítanie údajov z DataInputStream: 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);
    Zatvorte súbor:Nakoniec by mal byť každý súbor po vykonaní vstupných alebo výstupných operácií zatvorený, inak môžu byť poškodené údaje. Zatvorenie súboru sa vykoná zatvorením súvisiacich streamov. Napríklad fout.close(): zatvorí FileOutputStream, takže neexistuje spôsob, ako zapisovať údaje do súboru.
Implementácia: 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); 

Zlepšenie efektivity pomocou 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.
  • Predpokladajme, že údaje sa načítajú z klávesnice do pamäte pomocou DataInputStream a načítanie 1 znaku do pamäte trvá 1 sekundu a tento znak zapíše do súboru FileOutputStream, pričom strávi ďalšiu 1 sekundu.
  • Takže čítanie a zápis súboru bude trvať 200 sekúnd. To je strata času. Na druhej strane, ak sa použije trieda Buffered, poskytujú vyrovnávaciu pamäť, ktorá sa najskôr naplní znakmi z vyrovnávacej pamäte, ktoré môžu byť okamžite zapísané do súboru. Triedy s vyrovnávacou pamäťou by sa mali používať v spojení s inými triedami prúdu.
  • 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
Dôležité metódy triedy BufferedOutputStream:
    void flush() : Vyprázdni tento výstupný tok vo vyrovnávacej pamäti. void write(byte[] b int off int len) : Zapisuje len bajty zo zadaného bajtového poľa počnúc offsetom do tohto výstupného toku s vyrovnávacou pamäťou. void write (int b): Zapíše zadaný bajt do tohto výstupného toku s vyrovnávacou pamäťou.
výstup:
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 
Súvisiace články:
  • CharacterStream vs ByteStream
  • Trieda súborov v jazyku Java
  • Spracovanie súborov v jazyku Java pomocou FileWriter a FileReader
Vytvoriť kvíz