logo

Criando um arquivo usando FileOutputStream

A classe FileOutputStream pertence ao fluxo de bytes e armazena os dados na forma de bytes individuais. Ele pode ser usado para criar arquivos de texto. Um arquivo representa o armazenamento de dados em uma segunda mídia de armazenamento, como um disco rígido ou CD. Se um arquivo está disponível ou não ou pode ser criado depende da plataforma subjacente. Algumas plataformas, em particular, permitem que um arquivo seja aberto para gravação por apenas um FileOutputStream (ou outros objetos de gravação de arquivo) por vez. Nessas situações, os construtores desta classe falharão se o arquivo envolvido já estiver aberto. FileOutputStream destina-se a gravar fluxos de bytes brutos, como dados de imagem. Para escrever fluxos de caracteres, considere usar FileWriter. Métodos importantes:
    void fechar(): Fecha esse fluxo de saída de arquivo e libera todos os recursos do sistema associados a esse fluxo. finalização nula protegida() : Limpa a conexão com o arquivo e garante que o método close desse fluxo de saída de arquivo seja chamado quando não houver mais referências a esse fluxo. gravação nula (byte[] b): Grava b.length bytes da matriz de bytes especificada neste fluxo de saída de arquivo. void write(byte[] b int off int len): Grava len bytes da matriz de bytes especificada começando no deslocamento neste fluxo de saída de arquivo. void escrever (int b): Grava o byte especificado neste fluxo de saída de arquivo.
As etapas a seguir devem ser seguidas para criar um arquivo de texto que armazene alguns caracteres (ou texto):
    Lendo dados: 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 Envie dados para 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);
    Lendo dados 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);
    Feche o arquivo:Finalmente, qualquer arquivo deve ser fechado após realizar operações de entrada ou saída nele, caso contrário os dados do arquivo podem ser corrompidos. O fechamento do arquivo é feito fechando os fluxos associados. Por exemplo fout.close(): fechará FileOutputStream, portanto, não há como gravar dados no arquivo.
Implementação: 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); 

Melhorando a eficiência usando 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.
  • Suponhamos que os dados sejam lidos do teclado para a memória usando DataInputStream e que leve 1 segundo para ler 1 caractere na memória e que esse caractere seja gravado no arquivo por FileOutputStream gastando mais 1 segundo.
  • Portanto, para ler e gravar um arquivo levará 200 segundos. Isso está desperdiçando muito tempo. Por outro lado, se as classes Buffered forem usadas, elas fornecem um buffer que é primeiro preenchido com caracteres do buffer que podem ser imediatamente gravados no arquivo. Classes em buffer devem ser usadas em conexão com outras classes de fluxo.
  • 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étodos importantes da classe BufferedOutputStream:
    void flush() : Libera esse fluxo de saída em buffer. void write(byte[] b int off int len): Grava len bytes da matriz de bytes especificada começando no deslocamento para esse fluxo de saída em buffer. void escrever (int b): Grava o byte especificado neste fluxo de saída em buffer.
Saída:
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 
Artigos relacionados:
  • CharacterStream versus ByteStream
  • Classe de arquivo em Java
  • Manipulação de arquivos em Java usando FileWriter e FileReader
Criar questionário