2011-10-09 13 views
7

decir que tengo un archivo llamado "input.txt" que tiene un montón de números enteros positivos en ella:
Java: Leer matriz de enteros de archivo

6 
5 
6 
8 
6 
2 
4 

y así sucesivamente .... (un número entero por línea)

Quiero leer este archivo y convertirlo en una matriz. El primer entero (en este caso 6) indica el número de índices o elementos en la matriz, por lo que 6 puntos. Los otros números completan la matriz que comienza en 0. Entonces en el índice 0, el número es 5, en el índice 1 el número es 6, y así sucesivamente.

¿Alguien puede mostrarme cómo leer este archivo y convertirlo en una matriz llamada A y devolver los enteros en cada índice como n?

esto es lo que tengo hasta ahora:

import java.io.*; 
public class inputFile { 
    public static jobScheduleRecursive(int[] A, int i) 
    { 
     try 
    { 
     FileReader filereader = new FileReader("input.txt"); 
     BufferedReader bufferedreader = new BufferedReader(filereader); 
     String line = bufferedreader.readLine(); 
     //While we have read in a valid line 
     while (line != null) { 
      //Try to parse integer from the String line 
      try { 
       System.out.println(Integer.parseInt(line)); 
      } catch (NumberFormatException nfe) { 
       System.err.println("Failed to parse integer from line:" + line); 
       System.err.println(nfe.getMessage()); 
       System.exit(1); 
      } 
      line = bufferedreader.readLine(); 
     } 
    } 
    catch(FileNotFoundException filenotfoundexception) 
    { 
     System.out.println("File not found."); 
    } 
    catch(IOException ioexception) 
    { 
     System.out.println("File input error occured!"); 
     ioexception.printStackTrace(); 
    } 
    return A; 
} 

Creo que estoy haciendo algo totalmente erróneo. por favor ayuda.

+2

Suena como ... la tarea? –

+0

No tiene que ingresar el número de entradas en la primera línea si usa una estructura de lista para almacenar los números. Usted puede convertir fácilmente la Lista en una matriz (que como una longitud fija) una vez que haya terminado de leer llamando a list.toArray() –

Respuesta

12

El uso de un método Scanner y Scanner.nextInt(), puede resolver esto en sólo unas pocas líneas:

Scanner s = new Scanner(new File("input.txt")); 
int[] array = new int[s.nextInt()]; 
for (int i = 0; i < array.length; i++) 
    array[i] = s.nextInt(); 
+0

Looping para cada valor parece un mal rendimiento. – AndroidDev

+0

Puede haber soluciones más rápidas. No los exploraría hasta que se perfile la aplicación y se identifiquen los cuellos de botella. – aioobe

5

Creo que se necesita esto para las competiciones de ACM-:) Yo uso como plantilla siguiente:

import java.io.*; 
import java.util.*;  

public class Task { 

    private BufferedReader input; 
    private PrintWriter output; 
    private StringTokenizer stoken; 

    String fin = "input"; 
    String fout = "output"; 


    private void solve() { // some solving code... 
     int n = nextInt(); 
     int[] mas = new int[n]; 
     for (int i = 0; i<n; i++){ 
      mas[i] = nextInt(); 
     } 
    } 



    Task() throws IOException { 
     input = new BufferedReader(new FileReader(fin + ".txt")); 
     output = new PrintWriter(new FileWriter(fout + ".txt")); 

     solve(); 

     input.close(); 
     output.flush(); 
     output.close(); 
    } 


    int nextInt() { 
     return Integer.parseInt(nextToken()); 
    } 


    long nextLong() { 
     return Long.parseLong(nextToken()); 
    } 


    double nextFloat() { 
     return Float.parseFloat(nextToken()); 
    } 


    double nextDouble() { 
     return Double.parseDouble(nextToken()); 
    } 


    String nextToken() { 
     while ((stoken == null) || (!stoken.hasMoreTokens())) { 
      try { 
       String line = input.readLine(); 
       stoken = new StringTokenizer(line); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return stoken.nextToken(); 
    } 


    public static void main(String[] args) throws IOException { 
     new Task(); 
    } 

} 

En el método solve() puede ver cómo leer un número N (longitud de la siguiente secuencia numérica) y después de eso en un bucle (0..N) leo números enteros desde la entrada (en este caso, la entrada es un archivo) .

1
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class filee{ 
    public static void main(String[] args) throws FileNotFoundException { 
     File f = new File("l.txt"); 
     Scanner b = new Scanner(f); 
     int[] arr = new int[b.nextInt()]; 
      for(int i = 0; i < arr.length; i++){ 
       arr[i] = b.nextInt(); 
      } 
     for (int o : arr){ 
      System.out.println(o); 
     } 
    } 
} 
4

Java 8+

int[] ints = Files.lines(Paths.get("input.txt")) 
        .mapToInt(Integer::parseInt).toArray(); 
+0

También podría hacer Files.lines (Paths.get ("input.txt")). MapToInt (Integer :: parseInt) .boxed(); para obtener una lista de no primitivos. –

0

Si el archivo es un recurso classpath:

int[] ints = Files 
      .lines(Paths.get(ClassLoader.getSystemResource("input.txt") 
        .toURI())).mapToInt(Integer::parseInt).toArray(); 

Imprimir el contenido de un archivo:

Arrays.stream(ints).forEach(System.out::println); 
Cuestiones relacionadas