2016-03-29 2 views
2

J'ai lu un fichier texte qui ressemble à ceci:Lire fichier texte et convertir en tableau 2d int en fonction de l'entrée en Java

operationName1 Value 

Il y a un nombre variable de lignes, avec différentes opérations et la valeur correspondante. Je peux lire le fichier et obtenir un tableau de chaînes 2D en sortie. C'est mon code.

try{ 
    Path path = Paths.get("./myFile.txt"); 
    String[][] array = Files.lines(path) 
       .map(s -> s.split("\\s+", 2)) 
       .map(a -> new String[]{a[0], a[1]}) 
       .toArray(String[][]::new); 
    }catch(IOException e){ 
} 

Question: Comment pourrais-je changer mon code pour obtenir un tableau 2D int à la place, où operationName1 serait « 0 » et operationName2 serait « 1 » (il n'y a que deux opérations possibles, chacun étant défini par un particulier chaîne)?

Ce fichier texte:

operationOne 5 
OtherOp 999 
operationOne 8 
operationOne 2 

deviendrais ce tableau 2d int:

[[0,5],[1,999],[0,8],[0,2]] 

L'indice est trop importante. Donc la 1ère ligne du fichier texte est la 1ère ligne de mon tableau. PS: S'il y a une meilleure syntaxe (plus récente), je suis ouvert à la suggestion.

Merci beaucoup.

+0

Hey David, pourquoi ne pas utiliser la réponse de la question précédente et le personnaliser? –

+0

Vous avez la valeur dans 'a [0]'. Testez cette valeur et mappez-la au nombre correspondant 0 ou 1. –

+0

Pourquoi essayez-vous d'utiliser des flux ici? Prévoyez-vous d'utiliser le parallélisme? Si ce n'est pas le cas, la boucle simple serait probablement beaucoup plus lisible (et probablement un peu plus rapide). – Pshemo

Répondre

4

Si vous avez besoin de parallelism? ... cela pourrait être une approche

AtomicInteger atomicInteger = new AtomicInteger(0); 
Map<String, Integer> known = new ConcurrentHashMap<>(); 
Path path = Paths.get("./myFile.txt"); 
int[][] array = Files.lines(path) 
    .map(s -> s.split("\\s+", 2)) 
    .map(a -> new int[]{ 
     known.computeIfAbsent(a[0], 
       k -> atomicInteger.getAndIncrement()), 
     Integer.parseInt(a[1]) 
    }) 
    .toArray(int[][]::new); 
+1

ou voir: http://stackoverflow.com/questions/29878981/java-8-equivalent-to-getlinenumber-for-streams –

+1

Notez qu'il n'y a aucune raison d'utiliser 'Integer [] []' au lieu de 'int [ ] [] 'ici ... – Holger

+0

@Holger Je suis d'accord, le code est mis à jour –

1

J'utilise normalement la classe Scanner pour les fichiers texte de lecture

ArrayList<String[]> array = new ArrayList(); 
Scanner scan= new Scanner(new File("./myFile.txt")); 
String str; 
String auxiliary= new String[2]; 
while(scan.hasNextLine()){ 
    str= scan.readLine(); 
    auxiliary=str.split(" "); // you can use also the \\s 
    for(int i=0; i<array.size();i++){ 
     if(array.get(i)[0].equals(auxiliary[0])){ 
      String aux2[]={i,auxiliary[1]}; 
      break; 
     } 
    } 
    String aux2[]={array.size,auxiliary[1]}; 
} 

je l'espère, il a aidé.

# EDIT: Correction de quelques problèmes

+0

Quelques problèmes: (1) Scanner ne renvoie pas "null" lorsqu'il n'y a plus de lignes. Il jette une exception. Ainsi, au lieu de 'while (str! = NULL)' ((2) vous vouliez probablement dire 'null' - Java est sensible à la casse), vous devriez utiliser quelque chose comme' while (scan.hasNextLine()) '. (3) 'split' attend la chaîne' "" 'non char' '' 'comme argument. (Amélioration) Dans la plupart des cas, il n'est pas nécessaire d'utiliser 'split 'quand nous avons Scanner. Nous utilisons habituellement 'haveNext' ou' haveNext * Type * 'ici si nous savons combien d'éléments apparaîtront dans chaque ligne (il suffit d'utiliser 'hasNext()' au lieu de 'hasNextLine'). – Pshemo

+0

Merci. Au cours des 3 derniers mois, j'ai travaillé dur en C, j'ai échangé certaines choses. Mais j'ai réparé. –

1

Il est un peu long, mais il vous permet d'aller operationName1 ... operationNameN

J'essaie toujours de garder le code propre, donc si vous avez des questions il suffit de demander

public class Main { 

    public static void main(String[] args) throws IOException { 

      File file = new File("test.txt"); 
      BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); 

      ArrayList<String> operations = new ArrayList<String>(); 
      ArrayList<Point> points = new ArrayList<Point>(); 

      String line; 
      String[] array; 

      int index; 
      while((line = bufferedReader.readLine()) != null) 
      { 
       array = line.split(" "); 

       if((index = hasOperation(array[0], operations)) == -1) 
       { 
        operations.add(array[0]); 
        index = operations.size()-1; 
        points.add(new Point(index, Integer.parseInt(array[1]))); 
       } 
       else 
       { 
        points.add(new Point(index, Integer.parseInt(array[1]))); 
       } 
      } 

      System.out.print("["); 
      for(int i = 0; i < points.size()-1; i++) 
      { 
       System.out.print(points.get(i).toString() + ","); 
      } 
      System.out.println(points.get(points.size()-1).toString()+"]"); 
    } 



    public static int hasOperation(String operation, ArrayList<String> operations){ 

     for(int index = 0; index < operations.size(); index++) 
     { 
      if(operation.equalsIgnoreCase(operations.get(index))) 
       return index; 
     } 
     return -1; 
    } 

} 

public class Point { 
    public int x; 
    public int y; 


public Point(int x, int y){ 
     this.x = x; 
     this.y = y; 
    } 

    @Override 
    public String toString() 
    { 
     return "[" + x + "," + y + "]"; 
    } 
}