logo

Tiedoston luominen FileOutputStreamin avulla

FileOutputStream-luokka kuuluu tavuvirtaan ja tallentaa tiedot yksittäisten tavujen muodossa. Sitä voidaan käyttää tekstitiedostojen luomiseen. Tiedosto edustaa tietojen tallennusta toiselle tallennusvälineelle, kuten kiintolevylle tai CD:lle. Se, onko tiedosto saatavilla tai voidaanko se luoda, riippuu taustalla olevasta alustasta. Jotkin alustat mahdollistavat tiedoston avaamisen kirjoittamista varten vain yhdelle FileOutputStreamille (tai muille tiedostoa kirjoittaville objekteille) kerrallaan. Tällaisissa tilanteissa tämän luokan rakentajat epäonnistuvat, jos kyseessä oleva tiedosto on jo auki. FileOutputStream on tarkoitettu raakatavujen, kuten kuvatietojen, kirjoittamiseen. Harkitse FileWriterin käyttöä merkkivirtojen kirjoittamiseen. Tärkeitä menetelmiä:
    void close() : Sulkee tämän tiedoston tulostusvirran ja vapauttaa kaikki tähän tietovirtaan liittyvät järjestelmäresurssit. suojattu void finalize() : Puhdistaa yhteyden tiedostoon ja varmistaa, että tämän tiedoston tulostusvirran sulkemismenetelmä kutsutaan, kun tähän tietovirtaan ei ole enää viittauksia. void write (tavu[] b) : Kirjoittaa b.length tavua määritetystä tavutaulukosta tähän tiedoston tulostusvirtaan. void write(byte[] b int off int len) : Kirjoittaa len tavuja määritetystä tavutaulukosta alkaen offsetista tähän tiedoston tulostusvirtaan. tyhjä kirjoitus (int b): Kirjoittaa määritetyn tavun tähän tiedoston tulostusvirtaan.
Noudata seuraavia vaiheita luodaksesi tekstitiedoston, joka tallentaa joitain merkkejä (tai tekstiä):
    Tietojen lukeminen: 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 Lähetä tiedot OutputStreamiin: 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);
    Tietojen lukeminen DataInputStreamista: 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);
    Sulje tiedosto:Lopuksi mikä tahansa tiedosto tulee sulkea sen jälkeen, kun sille on suoritettu syöttö- tai tulostustoimintoja, muuten tiedostojen tiedot voivat vioittua. Tiedoston sulkeminen tapahtuu sulkemalla siihen liittyvät streamit. Esimerkiksi fout.close(): sulkee FileOutputStreamin, joten dataa ei voi kirjoittaa tiedostoon.
Toteutus: 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); 

Tehokkuuden parantaminen käyttämällä 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.
  • Oletetaan, että tiedot luetaan näppäimistöltä muistiin DataInputStreamin avulla ja yhden merkin lukeminen muistiin kestää 1 sekunti ja FileOutputStream kirjoittaa tämän merkin tiedostoon viemällä vielä 1 sekunti.
  • Joten tiedoston lukeminen ja kirjoittaminen kestää 200 sekuntia. Tämä tuhlaa paljon aikaa. Toisaalta, jos käytetään puskuroitua luokittelua, ne tarjoavat puskurin, joka täytetään ensin puskurista olevilla merkeillä, jotka voidaan kirjoittaa tiedostoon kerralla. Puskuroituja luokkia tulee käyttää muiden stream-luokkien yhteydessä.
  • 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
BufferedOutputStream-luokan tärkeitä menetelmiä:
    void flush() : Tyhjentää tämän puskuroidun lähtövirran. void write(byte[] b int off int len) : Kirjoittaa len tavuja määritetystä tavujoukosta alkaen offsetista tähän puskuroituun lähtövirtaan. tyhjä kirjoitus (int b): Kirjoittaa määritetyn tavun tähän puskuroituun lähtövirtaan.
Lähtö:
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 
Aiheeseen liittyviä artikkeleita:
  • CharacterStream vs ByteStream
  • Tiedostoluokka Javassa
  • Tiedostojen käsittely Javassa FileWriterin ja FileReaderin avulla
Luo tietokilpailu