Anteriormente vimos cómo crear un archivo en Java. En este tutorial veremos cómo escribir en un archivo java usando FileOutputStream
. Nosotros usaríamos método de escritura de FileOutputStream
para escribir el contenido en el archivo especificado. Aquí está la firma de write()
método.
public void write(byte[] b) throws IOException
El escribe b.length
bytes de la matriz de bytes especificada a este flujo de salida de archivo. Como puede ver, este método requiere una matriz de bytes para poder escribirlos en un archivo. Entonces necesitaríamos convertir nuestro contenido a una matriz de bytes antes de escribirlo en el archivo.
Código completo: escribir en un archivo
En el siguiente ejemplo estamos escribiendo un archivo String
en un archivo. Para convertir el String
en una matriz de bytes, estamos usando el método getBytes () de la clase String.
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WriteFileDemo { public static void main(String[] args) { FileOutputStream fos = null; File file; String mycontent = "This is my Data which needs" + " to be written into the file"; try { //Specify the file path here file = new File("C:/myfile.txt"); fos = new FileOutputStream(file); /* This logic will check whether the file * exists or not. If the file is not found * at the specified location it would create * a new file*/ if (!file.exists()) { file.createNewFile(); } /*String content cannot be directly written into * a file. It needs to be converted into bytes */ byte[] bytesArray = mycontent.getBytes(); fos.write(bytesArray); fos.flush(); System.out.println("File Written Successfully"); } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } } catch (IOException ioe) { System.out.println("Error in closing the Stream"); } } } }
Producción:
File Written Successfully