Archivo de texto completo a una cadena en Java


¿Java tiene una instrucción de una línea para leer en un archivo de texto, como la que tiene C#?

Quiero decir, ¿hay algo equivalente a esto en Java?:

String data = System.IO.File.ReadAllText("path to file");

Si no... cuál es la' manera óptima ' de hacer esto...?

Editar:
Prefiero una forma dentro de las bibliotecas estándar de Java... No puedo usar bibliotecas de terceros..

Author: dimo414, 2010-10-03

9 answers

AFAIK, no hay un solo liner con bibliotecas estándar. El enfoque típico con bibliotecas estándar sería algo como esto:

public static String readStream(InputStream is) {
    StringBuilder sb = new StringBuilder(512);
    try {
        Reader r = new InputStreamReader(is, "UTF-8");
        int c = 0;
        while ((c = r.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return sb.toString();
}

Notas:

  • para leer texto de file, utilice FileInputStream
  • si el rendimiento es importante y está leyendo archivos grandes, sería aconsejable envolver la secuencia en BufferedInputStream
  • la secuencia debe ser cerrada por el llamante
 20
Author: Neeme Praks,
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
2013-08-09 14:27:41

Apache commons-io tiene:

String str = FileUtils.readFileToString(file, "utf-8");

Pero no existe tal utilidad en las clases java estándar. Si (por alguna razón) no quiere bibliotecas externas, tendrías que reimplementar ella. Aquí hay algunos ejemplos, y alternativamente, puede ver cómo se implementa por commons-io o Guava.

 45
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
2010-10-03 12:49:27

No dentro de las bibliotecas Java principales, pero puede usar Guava :

String data = Files.asCharSource(new File("path.txt"), Charsets.UTF_8).read();

O para leer líneas:

List<String> lines = Files.readLines( new File("path.txt"), Charsets.UTF_8 );

Por supuesto, estoy seguro de que hay otras bibliotecas de terceros que lo harían igualmente fácil - estoy más familiarizado con la Guayaba.

 24
Author: Jon Skeet,
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-01-14 07:31:01

Java 7 mejora este lamentable estado de cosas con el Files class (no debe confundirse con la clase de Guayaba del mismo nombre ), puede obtener todas las líneas de un archivo - sin bibliotecas externas-con:

List<String> fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);

O en una cadena:

String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
// or equivalently:
StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(path)));

Si necesita algo fuera de la caja con un JDK limpio, esto funciona muy bien. Dicho esto, ¿por qué escribes Java sin Guayaba?

 22
Author: dimo414,
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-10-26 17:38:14

En Java 8 (sin bibliotecas externas) se pueden usar flujos. Este código lee un archivo y pone todas las líneas separadas por', ' en una cadena.

try (Stream<String> lines = Files.lines(myPath)) {
    list = lines.collect(Collectors.joining(", "));
} catch (IOException e) {
    LOGGER.error("Failed to load file.", e);
}
 8
Author: Kris,
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-05-04 11:07:20

Con JDK / 11, puede leer un archivo completo en un Path como una cadena usando Files.readString(Path path):

try {
    String fileContent = Files.readString(Path.of("/foo/bar/gus"));
} catch (IOException e) {
    // handle exception in i/o
}

La documentación del método del JDK dice lo siguiente:

/**
 * Reads all content from a file into a string, decoding from bytes to characters
 * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
 * The method ensures that the file is closed when all content have been read
 * or an I/O error, or other runtime exception, is thrown.
 *
 * <p> This method is equivalent to:
 * {@code readString(path, StandardCharsets.UTF_8) }
 *
 * @param   path the path to the file
 *
 * @return  a String containing the content read from the file
 *
 * @throws  IOException
 *          if an I/O error occurs reading from the file or a malformed or
 *          unmappable byte sequence is read
 * @throws  OutOfMemoryError
 *          if the file is extremely large, for example larger than {@code 2GB}
 * @throws  SecurityException
 *          In the case of the default provider, and a security manager is
 *          installed, the {@link SecurityManager#checkRead(String) checkRead}
 *          method is invoked to check read access to the file.
 *
 * @since 11
 */
public static String readString(Path path) throws IOException 
 2
Author: nullpointer,
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-09-12 17:59:16

No se necesitan bibliotecas externas. El contenido del archivo se almacenará en búfer antes de convertirlo en cadena.

Path path = FileSystems.getDefault().getPath(directory, filename);
String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
 2
Author: SzB,
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-09-24 05:28:22

Aquí hay 3 formas de leer un archivo de texto en una línea, sin necesidad de un bucle. Documenté 15 formas de leer desde un archivo en Java y estas son de ese artículo.

Tenga en cuenta que todavía tiene que recorrer la lista que se devuelve, a pesar de que la llamada real para leer el contenido del archivo requiere solo 1 línea, sin bucle.

1) java.nio.file.File.ReadAllLines () - Codificación predeterminada

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    List  fileLinesList = Files.readAllLines(file.toPath());

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}

2) java.nio.file.File.ReadAllLines () - Explicit Codificación

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines_Encoding {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    //use UTF-8 encoding
    List  fileLinesList = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}

3) java.nio.file.File.ReadAllBytes()

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class ReadFile_Files_ReadAllBytes {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    byte [] fileBytes = Files.readAllBytes(file.toPath());
    char singleChar;
    for(byte b : fileBytes) {
      singleChar = (char) b;
      System.out.print(singleChar);
    }
  }
}
 0
Author: gomisha,
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-09 13:02:20

No se necesitan bibliotecas externas. El contenido del archivo se almacenará en búfer antes de convertirlo en cadena.

  String fileContent="";
  try {
          File f = new File("path2file");
          byte[] bf = new byte[(int)f.length()];
          new FileInputStream(f).read(bf);
          fileContent = new String(bf, "UTF-8");
      } catch (FileNotFoundException e) {
          // handle file not found exception
      } catch (IOException e) {
          // handle IO-exception
      }
 0
Author: SzB,
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-09-24 05:25:21