¿Cómo puedo crear un archivo y escribir en Java?


¿Cuál es la forma más sencilla de crear y escribir en un archivo (de texto) en Java?

 1172
Author: Wolf, 2010-05-21

30 answers

Tenga en cuenta que cada una de las muestras de código a continuación puede lanzar IOException. Try/catch / finally los bloques han sido omitidos por brevedad. Vea este tutorial para obtener información sobre el manejo de excepciones.

Creando un archivo de texto (tenga en cuenta que esto sobrescribirá el archivo si ya existe):

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Creando un archivo binario (esto también sobrescribirá el archivo):

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7+ los usuarios pueden utilizar el Files clase para escribir en archivos:

Creando un archivo de texto:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
//Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.APPEND);

Creando un archivo binario:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
 1499
Author: Michael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-16 00:04:58

En Java 7 y arriba:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
              new FileOutputStream("filename.txt"), "utf-8"))) {
   writer.write("something");
}

Hay utilidades útiles para eso sin embargo:

Tenga en cuenta también que puede usar un FileWriter, pero utiliza la codificación predeterminada, lo que a menudo es una mala idea: es mejor especificar la codificación explícitamente.

A continuación se muestra la respuesta original, anterior a Java 7


Writer writer = null;

try {
    writer = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream("filename.txt"), "utf-8"));
    writer.write("Something");
} catch (IOException ex) {
    // Report
} finally {
   try {writer.close();} catch (Exception ex) {/*ignore*/}
}

Ver también: Lectura, Escribir y Crear Archivos (incluye NIO2).

 364
Author: Bozho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-27 17:55:37

Si ya tiene el contenido que desea escribir en el archivo (y no se genera sobre la marcha), el java.nio.file.Files la adición en Java 7 como parte de E/S nativa proporciona la forma más simple y eficiente de lograr sus objetivos.

Básicamente crear y escribir en un archivo es una sola línea, además una simple llamada a un método !

El siguiente ejemplo crea y escribe en 6 archivos diferentes para mostrar cómo se puede usar:

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("1st line", "2nd line");
byte[] data = {1, 2, 3, 4, 5};

try {
    Files.write(Paths.get("file1.bin"), data);
    Files.write(Paths.get("file2.bin"), data,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    Files.write(Paths.get("file3.txt"), "content".getBytes());
    Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
    Files.write(Paths.get("file5.txt"), lines, utf8);
    Files.write(Paths.get("file6.txt"), lines, utf8,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
    e.printStackTrace();
}
 118
Author: icza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-11 07:55:13
public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        BufferedWriter output = null;
        try {
            File file = new File("example.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write(text);
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
          if ( output != null ) {
            output.close();
          }
        }
    }
}
 70
Author: Eric Petroelje,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-13 23:04:45

Aquí hay un pequeño programa de ejemplo para crear o sobrescribir un archivo. Es la versión larga para que se pueda entender más fácilmente.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class writer {
    public void writing() {
        try {
            //Whatever the file path is.
            File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
            FileOutputStream is = new FileOutputStream(statText);
            OutputStreamWriter osw = new OutputStreamWriter(is);    
            Writer w = new BufferedWriter(osw);
            w.write("POTATO!!!");
            w.close();
        } catch (IOException e) {
            System.err.println("Problem writing to the file statsTest.txt");
        }
    }

    public static void main(String[]args) {
        writer write = new writer();
        write.writing();
    }
}
 39
Author: Draeven,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-17 20:22:44

Uso:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
    writer.write("text to write");
} 
catch (IOException ex) {
    // Handle me
}  

Usando try() se cerrará la secuencia automáticamente. Esta versión es corta, rápida (en búfer) y permite elegir la codificación.

Esta característica se introdujo en Java 7.

 31
Author: icl7126,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 15:54:24

Una forma muy sencilla de crear y escribir en un archivo en Java:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class CreateFiles {

    public static void main(String[] args) {
        try{
            // Create new file
            String content = "This is the content to write into create file";
            String path="D:\\a\\hi.txt";
            File file = new File(path);

            // If file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);

            // Write in file
            bw.write(content);

            // Close connection
            bw.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

Referencia: Archivo crear ejemplo en java

 30
Author: Java Rocks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 16:04:39

Aquí estamos introduciendo una cadena en un archivo de texto:

String content = "This is the content to write into a file";
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); // Be sure to close BufferedWriter

Podemos crear fácilmente un nuevo archivo y añadir contenido a él.

 17
Author: iKing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 15:56:22

Si desea tener una experiencia relativamente libre de dolor, también puede echar un vistazo al paquete Apache Commons IO, más específicamente al FileUtils clase .

Nunca se olvide de comprobar las bibliotecas de terceros. Joda-Hora para la manipulación de la fecha, Apache Commons Lang StringUtils para las operaciones de cadena comunes y tales pueden hacer que su código sea más legible.

Java es un gran lenguaje, pero la biblioteca estándar es a veces un poco de bajo nivel. Poderoso, pero de bajo nivel, sin embargo.

 15
Author: extraneon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-30 23:41:00

Dado que el autor no especificó si requieren una solución para las versiones de Java que han sido Eol'd (tanto por Sun como por IBM, y estos son técnicamente los JVM más extendidos), y debido al hecho de que la mayoría de la gente parece haber respondido a la pregunta del autor antes de que se especificara que es un archivo de texto (no binario), he decidido proporcionar mi respuesta.


En primer lugar, Java 6 generalmente ha llegado al final de la vida, y como el autor no especificó que necesita compatibilidad heredada, supongo que significa automáticamente Java 7 o superior (Java 7 aún no es Eol'd por IBM). Por lo tanto, podemos mirar directamente en el archivo de E / S tutorial: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html

Antes del lanzamiento de Java SE 7, la clase java. io. File era la mecanismo utilizado para E/S de archivos, pero tenía varios inconvenientes.

  • Muchos métodos no arrojaron excepciones cuando fallaron, por lo que fue imposible obtener un error útil mensaje. Por ejemplo, si un archivo la eliminación falló, el programa recibiría un "error de eliminación" pero no sabría si fuera porque el archivo no existía, el usuario no tener permisos, o había algún otro problema.
  • El método de renombrar no funcionó de manera consistente en todas las plataformas.
  • No hubo apoyo real para enlaces simbólicos.
  • Se deseaba más soporte para metadatos, tales como permisos de archivo, propietario de archivo y otros atributos de seguridad. Acceder los metadatos del archivo eran ineficientes.
  • Muchos de los métodos de Archivo no escala. Solicitar una gran lista de directorios a través de un servidor podría resultar en un colgar. Los directorios grandes también podrían causar problemas de recursos de memoria, resultando en una denegación de servicio.
  • No era posible escribir código confiable que podría recorrer recursivamente un árbol de archivos y responder apropiadamente si hubiera enlaces simbólicos circulares.

Oh bien, eso descarta java. io. File. If a el archivo no se puede escribir / anexar, es posible que ni siquiera pueda saber por qué.


Podemos seguir mirando el tutorial: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common

Si tiene todas las líneas que va a escribir (anexar) al archivo de texto por adelantado, el enfoque recomendado ser https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-

Aquí hay un ejemplo (simplificado):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);

Otro ejemplo (anexar):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);

Si desea escribir el contenido del archivo como usted go: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption...-

Ejemplo simplificado (Java 8 o superior):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
    writer.append("Zero header: ").append('0').write("\r\n");
    [...]
}

Otro ejemplo (anexar):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
    writer.write("----------");
    [...]
}

Estos métodos requieren un esfuerzo mínimo por parte del autor y deben ser preferidos a todos los demás cuando se escribe en archivos [text].

 11
Author: afk5min,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-27 18:38:29

Si por alguna razón desea separar el acto de crear y escribir, el equivalente Java de touch es

try {
   //create a file named "testfile.txt" in the current working directory
   File myFile = new File("testfile.txt");
   if ( myFile.createNewFile() ) {
      System.out.println("Success!");
   } else {
      System.out.println("Failure!");
   }
} catch ( IOException ioe ) { ioe.printStackTrace(); }

createNewFile() hace una comprobación de existencia y crea un archivo atómicamente. Esto puede ser útil si desea asegurarse de que fue el creador del archivo antes de escribirlo, por ejemplo.

 9
Author: Mark Peters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-21 20:12:21

Uso:

JFileChooser c = new JFileChooser();
c.showOpenDialog(c);
File writeFile = c.getSelectedFile();
String content = "Input the data here to be written to your file";

try {
    FileWriter fw = new FileWriter(writeFile);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(content);
    bw.append("hiiiii");
    bw.close();
    fw.close();
}
catch (Exception exc) {
   System.out.println(exc);
}
 9
Author: Rohit ZP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 15:58:30

Creo que este es el camino más corto:

FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write
// your file extention (".txt" in this case)
fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!
fr.close();
 8
Author: ben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 16:00:34

Para crear un archivo sin sobrescribir el archivo existente:

System.out.println("Choose folder to create file");
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.showOpenDialog(c);
c.getSelectedFile();
f = c.getSelectedFile(); // File f - global variable
String newfile = f + "\\hi.doc";//.txt or .doc or .html
File file = new File(newfile);

try {
    //System.out.println(f);
    boolean flag = file.createNewFile();

    if(flag == true) {
        JOptionPane.showMessageDialog(rootPane, "File created successfully");
    }
    else {
        JOptionPane.showMessageDialog(rootPane, "File already exists");
    }
    /* Or use exists() function as follows:
        if(file.exists() == true) {
            JOptionPane.showMessageDialog(rootPane, "File already exists");
        }
        else {
            JOptionPane.showMessageDialog(rootPane, "File created successfully");
        }
    */
}
catch(Exception e) {
    // Any exception handling method of your choice
}
 7
Author: aashima,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 15:57:17
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
    public static void main(String [] args) {
        FileWriter fw= null;
        File file =null;
        try {
            file=new File("WriteFile.txt");
            if(!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            fw.write("This is an string written to a file");
            fw.flush();
            fw.close();
            System.out.println("File written Succesfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 6
Author: Anurag Goel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-20 10:29:10
package fileoperations;
import java.io.File;
import java.io.IOException;

public class SimpleFile {
    public static void main(String[] args) throws IOException {
        File file =new File("text.txt");
        file.createNewFile();
        System.out.println("File is created");
        FileWriter writer = new FileWriter(file);

        // Writes the content to the file
        writer.write("Enter the text that you want to write"); 
        writer.flush();
        writer.close();
        System.out.println("Data is entered into file");
    }
}
 6
Author: Suthan Srinivasan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-20 12:01:03

¡Una sola línea ! path y line son Cadenas

import java.nio.file.Files;
import java.nio.file.Paths;

Files.write(Paths.get(path), lines.getBytes());
 5
Author: Ran Adler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-10 05:32:40

La forma más sencilla que puedo encontrar:

Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
    writer.write("Hello, world!");
}

Probablemente solo funcionará para 1.7+.

 5
Author: qed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 15:59:18

Si estamos usando Java 7 y superior y también conocemos el contenido a añadir (anexado) al archivo podemos hacer uso del método newBufferedWriter en el paquete NIO.

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Hay pocos puntos a tener en cuenta:

  1. Siempre es un buen hábito especificar la codificación del conjunto de caracteres y para eso tenemos constante en la clase StandardCharsets.
  2. El código utiliza la instrucción try-with-resource en la que los recursos se cierran automáticamente después del intento.

Aunque OP no ha pedido, pero por si acaso queremos buscar líneas que tengan alguna palabra clave específica, por ejemplo confidential podemos hacer uso de las API de stream en Java:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}
 4
Author: i_am_zero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-21 07:00:19

Lectura y escritura de archivos usando input y outputstream:

//Coded By Anurag Goel
//Reading And Writing Files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class WriteAFile {
    public static void main(String args[]) {
        try {
            byte array [] = {'1','a','2','b','5'};
            OutputStream os = new FileOutputStream("test.txt");
            for(int x=0; x < array.length ; x++) {
                os.write( array[x] ); // Writes the bytes
            }
            os.close();

            InputStream is = new FileInputStream("test.txt");
            int size = is.available();

            for(int i=0; i< size; i++) {
                System.out.print((char)is.read() + " ");
            }
            is.close();
        } catch(IOException e) {
            System.out.print("Exception");
        }
    }
}
 4
Author: Anurag Goel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 15:59:48

Solo incluye este paquete:

java.nio.file

Y luego puedes usar este código para escribir el archivo:

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);
 4
Author: Arsalan Hussain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 16:01:01

Vale la pena probar Java 7+:

 Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());

Parece prometedor...

 4
Author: Sherlock Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 16:06:59

Para múltiples archivos puede usar:

static void out(String[] name, String[] content) {

    File path = new File(System.getProperty("user.dir") + File.separator + "OUT");

    for (File file : path.listFiles())
        if (!file.isDirectory())
            file.delete();
    path.mkdirs();

    File c;

    for (int i = 0; i != name.length; i++) {
        c = new File(path + File.separator + name[i] + ".txt");
        try {
            c.createNewFile();
            FileWriter fiWi = new FileWriter(c.getAbsoluteFile());
            BufferedWriter buWi = new BufferedWriter(fiWi);
            buWi.write(content[i]);
            buWi.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Está funcionando muy bien.

 4
Author: Tobias Brohl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 16:09:27

Estas son algunas de las formas posibles de crear y escribir un archivo en Java :

Usando FileOutputStream

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
  bw.write("Write somthing to the file ...");
  bw.newLine();
  bw.close();
} catch (FileNotFoundException e){
  // File was not found
  e.printStackTrace();
} catch (IOException e) {
  // Problem when writing to the file
  e.printStackTrace();
}

Usando FileWriter

try {
  FileWriter fw = new FileWriter("myOutFile.txt");
  fw.write("Example of content");
  fw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

Usando PrintWriter

try {
  PrintWriter pw = new PrintWriter("myOutFile.txt");
  pw.write("Example of content");
  pw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

Usando OutputStreamWriter

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  osw.write("Soe content ...");
  osw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

Para más información, consulte este tutorial sobre cómo leer y escribir archivos en Java.

 4
Author: Mehdi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-04 15:51:09

Hay algunas maneras simples, como:

File file = new File("filename.txt");
PrintWriter pw = new PrintWriter(file);

pw.write("The world I'm coming");
pw.close();

String write = "Hello World!";

FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

fw.write(write);

fw.close();
 3
Author: imvp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 16:02:47

Incluso puede crear un archivo temporal usando una propiedad del sistema , que será independiente del sistema operativo que esté utilizando.

File file = new File(System.*getProperty*("java.io.tmpdir") +
                     System.*getProperty*("file.separator") +
                     "YourFileName.txt");
 3
Author: Muhammed Sayeed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 16:07:52

Usando la biblioteca de Guayaba de Google, podemos crear y escribir en un archivo muy facilmente.

package com.zetcode.writetofileex;

import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;

public class WriteToFileEx {

    public static void main(String[] args) throws IOException {

        String fileName = "fruits.txt";
        File file = new File(fileName);

        String content = "banana, orange, lemon, apple, plum";

        Files.write(content.getBytes(), file);
    }
}

El ejemplo crea un nuevo archivo fruits.txt en el directorio raíz del proyecto.

 2
Author: Jan Bodnar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-15 13:40:00

Leyendo la colección con los clientes y guardándola en el archivo, con JFileChooser.

private void writeFile(){

    JFileChooser fileChooser = new JFileChooser(this.PATH);
    int retValue = fileChooser.showDialog(this, "Save File");

    if (retValue == JFileChooser.APPROVE_OPTION){

        try (Writer fileWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileChooser.getSelectedFile())))){

            this.customers.forEach((c) ->{
                try{
                    fileWrite.append(c.toString()).append("\n");
                }
                catch (IOException ex){
                    ex.printStackTrace();
                }
            });
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}
 2
Author: hasskell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 16:05:52

La mejor manera es usar Java7: Java 7 introduce una nueva forma de trabajar con el sistema de archivos, junto con una nueva utilidad class – Files. Usando la clase Files, también podemos crear, mover, copiar, eliminar archivos y directorios; también se puede usar para leer y escribir en un archivo.

public void saveDataInFile(String data) throws IOException {
    Path path = Paths.get(fileName);
    byte[] strToBytes = data.getBytes();

    Files.write(path, strToBytes);
}

Escribir con FileChannel Si está tratando con archivos grandes, FileChannel puede ser más rápido que el IO estándar. El siguiente código escribe una cadena en un archivo usando FileChannel:

public void saveDataInFile(String data) 
  throws IOException {
    RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
    FileChannel channel = stream.getChannel();
    byte[] strBytes = data.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
    buffer.put(strBytes);
    buffer.flip();
    channel.write(buffer);
    stream.close();
    channel.close();
}

Escribir con DataOutputStream

public void saveDataInFile(String data) throws IOException {
    FileOutputStream fos = new FileOutputStream(fileName);
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
    outStream.writeUTF(data);
    outStream.close();
}

Escribir con FileOutputStream

Veamos ahora cómo podemos usar FileOutputStream para escribir datos binarios en un archivo. El siguiente código convierte una cadena int bytes y escribe los bytes en un archivo usando un FileOutputStream:

public void saveDataInFile(String data) throws IOException {
    FileOutputStream outputStream = new FileOutputStream(fileName);
    byte[] strToBytes = data.getBytes();
    outputStream.write(strToBytes);

    outputStream.close();
}

Escribir con PrintWriter podemos usar un PrintWriter para escribir texto formateado en un archivo:

public void saveDataInFile() throws IOException {
    FileWriter fileWriter = new FileWriter(fileName);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print("Some String");
    printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
    printWriter.close();
}

Escribir con BufferedWriter: utilizar BufferedWriter para escribir una cadena en un archivo nuevo:

public void saveDataInFile(String data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    writer.write(data);

    writer.close();
}

Añadir una cadena al archivo existente:

public void saveDataInFile(String data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
    writer.append(' ');
    writer.append(data);

    writer.close();
}
 2
Author: sajad abbasi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-22 13:41:11

En Java 8 use Archivos y rutas y use la construcción try-with-resources.

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WriteFile{
    public static void main(String[] args) throws IOException {
        String file = "text.txt";
        System.out.println("Writing to file: " + file);
        // Files.newBufferedWriter() uses UTF-8 encoding by default
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(file))) {
            writer.write("Java\n");
            writer.write("Python\n");
            writer.write("Clojure\n");
            writer.write("Scala\n");
            writer.write("JavaScript\n");
        } // the file will be automatically closed
    }
}
 1
Author: praveenraj4ever,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-14 04:53:53