logo

Crear un archivo usando FileOutputStream

La clase FileOutputStream pertenece al flujo de bytes y almacena los datos en forma de bytes individuales. Se puede utilizar para crear archivos de texto. Un archivo representa el almacenamiento de datos en un segundo medio de almacenamiento como un disco duro o un CD. El hecho de que un archivo esté disponible o pueda crearse depende de la plataforma subyacente. Algunas plataformas en particular permiten que un archivo se abra para escribirlo mediante un solo FileOutputStream (u otros objetos de escritura de archivos) a la vez. En tales situaciones, los constructores de esta clase fallarán si el archivo involucrado ya está abierto. FileOutputStream está diseñado para escribir flujos de bytes sin formato, como datos de imágenes. Para escribir secuencias de caracteres, considere usar FileWriter. Métodos importantes:
    cierre vacío() : Cierra el flujo de salida de este archivo y libera todos los recursos del sistema asociados con este flujo. finalizar vacío protegido() : Limpia la conexión al archivo y garantiza que se llame al método de cierre de esta secuencia de salida de archivo cuando no haya más referencias a esta secuencia. escritura nula (byte [] b): Escribe b.length bytes de la matriz de bytes especificada en este flujo de salida de archivo. escritura nula (byte [] b int off int len): Escribe len bytes de la matriz de bytes especificada comenzando en el desplazamiento en este flujo de salida de archivo. escritura nula (int b): Escribe el byte especificado en el flujo de salida de este archivo.
Se deben seguir los siguientes pasos para crear un archivo de texto que almacene algunos caracteres (o texto):
    Datos 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 Enviar datos 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);
    Leyendo datos 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);
    Cierra el archivo:Finalmente, cualquier archivo debe cerrarse después de realizar operaciones de entrada o salida en él, de lo contrario los datos pueden dañarse. El cierre del archivo se realiza cerrando las secuencias asociadas. Por ejemplo, fout.close(): cerrará FileOutputStream, por lo que no hay forma de escribir datos en el archivo.
Implementación: 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); 

Mejora de la eficiencia mediante 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.
  • Supongamos que los datos se leen desde el teclado a la memoria usando DataInputStream y se necesita 1 segundo para leer 1 carácter en la memoria y FileOutputStream escribe este carácter en el archivo al pasar otro 1 segundo.
  • Entonces, leer y escribir un archivo tomará 200 segundos. Esto es una pérdida de tiempo. Por otro lado, si se utilizan las clases en búfer, proporcionan un búfer que primero se llena con caracteres del búfer que se pueden escribir de inmediato en el archivo. Las clases almacenadas en búfer deben usarse en conexión con otras clases de flujo.
  • 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 de la clase BufferedOutputStream:
    descarga vacía() : Vacía este flujo de salida almacenado en el búfer. escritura nula (byte [] b int off int len): Escribe len bytes de la matriz de bytes especificada comenzando en el desplazamiento en este flujo de salida almacenado en búfer. escritura nula (int b): Escribe el byte especificado en este flujo de salida almacenado en búfer.
Producción:
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 
Artículos relacionados:
  • CharacterStream y ByteStream
  • Clase de archivo en Java
  • Manejo de archivos en Java usando FileWriter y FileReader
Crear cuestionario