2010-10-03 21 views
40

¿Tiene Java una instrucción de una línea para leer en un archivo de texto, como lo que C# tiene?Archivo de texto completo en una cadena en Java

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

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

Si no ... ¿cuál es la 'mejor manera' de hacer esto ...?

Editar:
prefiero una forma dentro de las bibliotecas estándar de Java ... No puedo usar las bibliotecas 3 ª parte ..

+0

me encontré con este post es útil para mí. http://stackoverflow.com/questions/7463414/what-s-the-best-way-to-load-a-jsonobject-from-a-json-text-file –

Respuesta

17

AFAIK, no hay una sola línea con bibliotecas estándar. 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:

  • con el fin de texto de lectura de archivo, utilice FileInputStream
  • si el rendimiento es importante y están leyendo archivos de gran tamaño, sería recomendable ajustar la secuencia en BufferedInputStream
  • la corriente debe ser cerrado por el llamador
+2

lector de buffer tiene una línea de lectura que sería mejor que leer un char a la vez – Steven

+0

Si usaría un BufferedInputStream, no haría la diferencia –

+0

De esta manera agrega último (-1) a la cadena. – Alec

20

no dentro de las principales bibliotecas de Java, pero se puede utilizar 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 así de fácil: estoy casi familiarizado con Guava.

39

apache commons-io tiene:

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

Pero no hay tal utilidad en las clases estándar de Java. Si (por alguna razón) no quieres bibliotecas externas, tendrías que volver a implementarlas. Here son algunos ejemplos y, como alternativa, puede ver cómo lo implementa commons-io o Guava.

+4

Usaría 'FileUtils.readFileToString (archivo, codificación) 'versión - ¡también puede recomendar buenos hábitos! – Nick

+0

@Nick - gracias por la sugerencia – Bozho

19

Java 7 mejora en este lamentable estado de cosas con la clase Files (que no debe confundirse con la guayaba de class of the same name), puede obtener todas las líneas de un archivo - sin externa - bibliotecas 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 limpia esto funciona muy bien. Dicho esto, ¿por qué estás escribiendo Java sin guayaba?

3
Path path = FileSystems.getDefault().getPath(directory, filename); 
String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); 
+1

Nota ['String (byte [], String)'] (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String%28byte [],% 20java. lang.String% 29) arroja una 'UnsupportedEncodingException'. Deberías preferir el ['String (byte [], Charset)'] (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String%28byte [],% 20java.nio.charset.Charset% 29) constructor junto con las constantes en ['StandardCharsets'] (http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html) o Guava ['Charsets'] (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Charsets.html). – dimo414

1
String fileContent=""; 
    try { 
      File f = new File("path2file"); 
      FileInputStream inp = new FileInputStream(f); 
      byte[] bf = new byte[(int)f.length()]; 
      inp.read(bf); 
      fileContent = new String(bf, "UTF-8"); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
8

En Java 8 (no hay bibliotecas externas) se puede usar corrientes. Este código lee un archivo y coloca 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); 
} 
0

utilizan el método fileContentsFromLocalFilePath() en el Test clase se proporciona a continuación:

import org.apache.commons.io.IOUtils; 

import java.io.*; 

public class Test 
{ 
    private static String fileContentsFromLocalFilePath(String localFilePath) 
    { 
     //initially empty file content 
     String emptyContent = ""; 

     try 
     { 
      //we assume that file exists 
      File localFile = new File(localFilePath); 

      //if local file does not exist (as a directory or a file); 
      //else if local file does exist, but does not refer to file; throw exception 
      if(!localFile.exists() || (localFile.exists() && !localFile.isFile())) 
       throw new IllegalArgumentException("Provided path: " + localFilePath + "does not exist or it does not refer to a file"); 


      //at this point localFile exists and it is actually a file 
      InputStream inputStream = new FileInputStream(localFile); 

      //write the result to String writer 
      StringWriter writer = new StringWriter(); 
      IOUtils.copy(inputStream, writer, "UTF-8"); 


      //return the file contents string 
      return writer.toString(); 
     } // try 
     catch(Exception ex) 
     { 
      //report the exception to the user 
      ex.printStackTrace(); 

      //in other cases return empty string 
      return emptyContent; 
     } // catch 
    } // fileContentsFromLocalFilePath 

} // Test 
Cuestiones relacionadas