2010-09-27 25 views

Respuesta

46

de archivos de lectura, analizar cada línea en un entero y almacenar en una lista:

List<Integer> list = new ArrayList<Integer>(); 
File file = new File("file.txt"); 
BufferedReader reader = null; 

try { 
    reader = new BufferedReader(new FileReader(file)); 
    String text = null; 

    while ((text = reader.readLine()) != null) { 
     list.add(Integer.parseInt(text)); 
    } 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     if (reader != null) { 
      reader.close(); 
     } 
    } catch (IOException e) { 
    } 
} 

//print out the list 
System.out.println(list); 
+0

Esto es bueno, pero yo usaría 'Integer.valueOf (String) 'en su lugar, ya que desea un objeto (entero) de todos modos. –

+0

¿Por qué no podemos mover ** reader.close(); ** a la línea justo después del ciclo while y evitar todo el bloque ** finally ** y el otro ** try-catch ** bloquear el ** finalmente ** contiene? –

+2

@ m-d Consulte el [Tutorial de Java] (http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html). Debería cerrar los recursos en un 'finally' para asegurarse de que estén siempre cerrados incluso si se produce una excepción dentro del bloque' try'. Esto evita fugas de recursos. – dogbane

3
try{ 

    BufferedReader br = new BufferedReader(new FileReader("textfile.txt")); 
    String strLine; 
    //Read File Line By Line 
    while ((strLine = br.readLine()) != null) { 
     // Print the content on the console 
     System.out.println (strLine); 
    } 
    //Close the input stream 
    in.close(); 
    }catch (Exception e){//Catch exception if any 
     System.err.println("Error: " + e.getMessage()); 
    }finally{ 
    in.close(); 
    } 

Esto permitirá la lectura línea por línea,

Si tu no. son saperated por newline char. a continuación, en lugar de

System.out.println (strLine); 

Puede tener

try{ 
int i = Integer.parseInt(strLine); 
}catch(NumberFormatException npe){ 
//do something 
} 

Si está separada por espacios continuación

try{ 
    String noInStringArr[] = strLine.split(" "); 
//then you can parse it to Int as above 
    }catch(NumberFormatException npe){ 
    //do something 
    } 
+0

que debe cerrar el flujo de entrada en un bloque 'finally'. – dogbane

+0

No use DataInputStream para leer texto. Lamentablemente, ejemplos como este se copian una y otra vez, así que puedes eliminarlo de tu ejemplo. http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html –

+1

actualizado, buen artículo por cierto –

9

A mucho s alternativa Horter es a continuación:

Path filePath = Paths.get("file.txt"); 
Scanner scanner = new Scanner(filePath); 
List<Integer> integers = new ArrayList<>(); 
while (scanner.hasNext()) { 
    if (scanner.hasNextInt()) { 
     integers.add(scanner.nextInt()); 
    } else { 
     scanner.next(); 
    } 
} 

Un escáner rompe su entrada en tokens utilizando un patrón delimitador, que por defecto coincide con espacios en blanco. Aunque el delimitador predeterminado es un espacio en blanco, encontró con éxito todos los enteros separados por un nuevo carácter de línea.

3

Buenas noticias en Java 8 podemos hacerlo en una sola línea:

List<Integer> ints = Files.lines(Paths.get(fileName)) 
          .map(Integer::parseInt) 
          .collect(Collectors.toList()); 
1
File file = new File("file.txt"); 
Scanner scanner = new Scanner(file); 
List<Integer> integers = new ArrayList<>(); 
while (scanner.hasNext()) { 
    if (scanner.hasNextInt()) { 
     integers.add(scanner.nextInt()); 
    } 
    else { 
     scanner.next(); 
    } 
} 
System.out.println(integers); 
+0

¡Me gusta tu respuesta! La forma en que imprime enteros solamente y omite espacios, líneas nuevas y otros caracteres no enteros – Hazmat

Cuestiones relacionadas