logo

Creació d'un fitxer amb FileOutputStream

La classe FileOutputStream pertany al flux de bytes i emmagatzema les dades en forma de bytes individuals. Es pot utilitzar per crear fitxers de text. Un fitxer representa l'emmagatzematge de dades en un segon suport d'emmagatzematge com un disc dur o un CD. Si un fitxer està disponible o es pot crear depèn de la plataforma subjacent. Algunes plataformes en particular permeten obrir un fitxer per escriure només un FileOutputStream (o altres objectes d'escriptura de fitxers) alhora. En aquestes situacions, els constructors d'aquesta classe fallaran si el fitxer implicat ja està obert. FileOutputStream està pensat per escriure fluxos de bytes en brut com ara dades d'imatge. Per escriure fluxos de caràcters, considereu utilitzar FileWriter. Mètodes importants:
    void close(): Tanca aquest flux de sortida del fitxer i allibera tots els recursos del sistema associats amb aquest flux. protegit void finalize(): Neteja la connexió amb el fitxer i assegura que es crida al mètode de tancament d'aquest flux de sortida del fitxer quan no hi ha més referències a aquest flux. void write(byte[] b): Escriu bytes b.length de la matriu de bytes especificada en aquest flux de sortida de fitxer. void write(byte[] b int off int len): Escriu len bytes de la matriu de bytes especificada a partir de l'offset en aquest flux de sortida del fitxer. void write(int b): Escriu el byte especificat en aquest flux de sortida del fitxer.
S'han de seguir els passos següents per crear un fitxer de text que emmagatzemi alguns caràcters (o text):
    Dades de lectura: 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 Envia dades a 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);
    Llegint dades de 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);
    Tanqueu el fitxer:Finalment, qualsevol fitxer s'hauria de tancar després d'haver-hi realitzat operacions d'entrada o sortida, sinó les dades es podrien corrompre. El tancament del fitxer es fa tancant els fluxos associats. Per exemple fout.close(): tancarà el FileOutputStream, per tant no hi ha manera d'escriure dades al fitxer.
Implementació: 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); 

Millora de l'eficiència mitjançant 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.
  • Suposem que les dades es llegeixen des del teclat a la memòria mitjançant DataInputStream i que es triga 1 segon a llegir 1 caràcter a la memòria i FileOutputStream escriu aquest caràcter al fitxer passant 1 segon més.
  • Per tant, per llegir i escriure un fitxer trigarà 200 segons. Això fa perdre molt de temps. D'altra banda, si s'utilitzen els buffer classats, proporcionen un buffer que s'omple primer amb caràcters del buffer que es poden escriure alhora al fitxer. Les classes emmagatzemades s'han d'utilitzar en connexió amb altres classes de flux.
  • 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
Mètodes importants de la classe BufferedOutputStream:
    void flush(): Esborra aquest flux de sortida de buffer. void write(byte[] b int off int len): Escriu len bytes de la matriu de bytes especificada començant des de l'offset en aquest flux de sortida a la memòria intermèdia. void write(int b): Escriu el byte especificat en aquest flux de sortida de memòria intermèdia.
Sortida:
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 
Articles relacionats:
  • CharacterStream vs ByteStream
  • Classe de fitxer a Java
  • Gestió de fitxers en Java mitjançant FileWriter i FileReader
Crea un qüestionari