logo

Creazione di un file utilizzando FileOutputStream

La classe FileOutputStream appartiene al flusso di byte e memorizza i dati sotto forma di singoli byte. Può essere utilizzato per creare file di testo. Un file rappresenta la memorizzazione dei dati su un secondo supporto di memorizzazione come un disco rigido o un CD. La disponibilità o la possibilità di creare un file dipende dalla piattaforma sottostante. Alcune piattaforme in particolare consentono l'apertura di un file per la scrittura da un solo FileOutputStream (o altri oggetti di scrittura di file) alla volta. In tali situazioni i costruttori di questa classe falliranno se il file coinvolto è già aperto. FileOutputStream è pensato per scrivere flussi di byte grezzi come i dati di immagine. Per scrivere flussi di caratteri, considera l'utilizzo di FileWriter. Metodi importanti:
    vuoto vicino() : Chiude questo flusso di output del file e rilascia tutte le risorse di sistema associate a questo flusso. finalizzazione del vuoto protetto() : Pulisce la connessione al file e garantisce che il metodo di chiusura di questo flusso di output del file venga chiamato quando non sono più presenti riferimenti a questo flusso. void write(byte[] b): Scrive b.length byte dall'array di byte specificato nel flusso di output del file. void write(byte[] b int off int len) : Scrive len byte dall'array di byte specificato a partire da offset off nel flusso di output del file. void write(int b): Scrive il byte specificato nel flusso di output del file.
È necessario seguire i seguenti passaggi per creare un file di testo che memorizzi alcuni caratteri (o testo):
    Lettura dei dati: 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 Invia dati 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);
    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);
    Chiudi il file:Infine, qualsiasi file deve essere chiuso dopo aver eseguito operazioni di input o output su di esso, altrimenti i dati potrebbero essere danneggiati. La chiusura del file viene eseguita chiudendo i flussi associati. Ad esempio fout.close(): chiuderà FileOutputStream quindi non c'è modo di scrivere dati nel file.
Attuazione: 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); 

Miglioramento dell'efficienza utilizzando 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.
  • Supponiamo che i dati vengano letti dalla tastiera in memoria utilizzando DataInputStream e che sia necessario 1 secondo per leggere 1 carattere in memoria e questo carattere venga scritto nel file da FileOutputStream impiegando un altro 1 secondo.
  • Quindi per leggere e scrivere un file ci vorranno 200 sec. Questo fa perdere molto tempo. D'altra parte, se vengono utilizzate le classi Buffered, forniscono un buffer che viene prima riempito con caratteri dal buffer che possono essere immediatamente scritti nel file. Le classi memorizzate nel buffer dovrebbero essere utilizzate in connessione ad altre classi di flusso.
  • 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
    svuotamento vuoto() : Svuota questo flusso di output memorizzato nel buffer. void write(byte[] b int off int len) : Scrive len byte dall'array di byte specificato a partire da offset off in questo flusso di output memorizzato nel buffer. void write(int b): Scrive il byte specificato in questo flusso di output memorizzato nel buffer.
Produzione:
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 
Articoli correlati:
  • CharacterStream contro ByteStream
  • Classe di file in Java
  • Gestione dei file in Java utilizzando FileWriter e FileReader
Crea quiz