Java - cómo escribo un archivo en un directorio especificado


Quiero escribir un archivo de resultados.txt a un directorio específico en mi máquina (Z:\results para ser precisos). ¿Cómo puedo especificar el directorio a BufferedWriter / FileWriter?

Actualmente, escribe el archivo correctamente pero en el directorio donde se encuentra mi código fuente. Gracias

    public void writefile(){

    try{
        Writer output = null;
        File file = new File("results.txt");
        output = new BufferedWriter(new FileWriter(file));

        for(int i=0; i<100; i++){
           //CODE TO FETCH RESULTS AND WRITE FILE
        }

        output.close();
        System.out.println("File has been written");

    }catch(Exception e){
        System.out.println("Could not create file");
    }
}
Author: user726219, 2011-04-27

3 answers

Uso:

File file = new File("Z:\\results\\results.txt");

Necesita duplicar las barras invertidas en Windows porque el carácter de barra invertida en sí es un escape en las cadenas literales de Java.

Para el sistema POSIX como Linux, simplemente use la ruta de archivo predeterminada sin duplicar la barra diagonal. esto se debe a que la barra diagonal no es un carácter de escape en Java.

File file = new File("/home/userName/Documents/results.txt");
 22
Author: Greg Hewgill,
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-02-01 09:55:47

Debe usar el constructor secundario para File para especificar el directorio en el que se va a crear simbólicamente. Esto es importante porque las respuestas que dicen crear un archivo anteponiendo el nombre del directorio al nombre original, no son tan independientes del sistema como este método.

Código de ejemplo:

String dirName = /* something to pull specified dir from input */;

String fileName = "test.txt";
File dir = new File (dirName);
File actualFile = new File (dir, fileName);

/* rest is the same */

Espero que ayude.

 34
Author: Kaushik Shankar,
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
2011-04-26 22:45:12

Simplemente coloque la ubicación del directorio completo en el objeto File.

File file = new File("z:\\results.txt");
 4
Author: Collin Price,
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
2011-04-26 22:28:56