Trier un fichier
Résolu
bloomingdals
-
bloomingdals -
bloomingdals -
Bonjour,
j'ai un fichier texte qui contient des lignes comme suit:
24
23
24
48
12
8
...
j'aimerai faire un tri sur ces nombre en comptant les nombre d'occurence de chaque nombre puis renvoyer le résultat dans un fichier comme suit
fichier 24 --> contient 2
fichier 23 --> contient 1
ect...
je sais pas comment faire pourriez vous m'aidez merci
j'ai un fichier texte qui contient des lignes comme suit:
24
23
24
48
12
8
...
j'aimerai faire un tri sur ces nombre en comptant les nombre d'occurence de chaque nombre puis renvoyer le résultat dans un fichier comme suit
fichier 24 --> contient 2
fichier 23 --> contient 1
ect...
je sais pas comment faire pourriez vous m'aidez merci
3 réponses
-
Tu ouvres ton fichier texte, tu lis les lignes une par une en les stockant dans une Map<Integer,Integer> dont soit la valeur n'existe pas et elle est initialisée à 1, soit elle existe et elle est incrémentée.
Remarque :
Quand tu fais "fichier 24 --> contient 2, fichier 23 --> contient 1" où est le tri ? -
c'est à dire le nombre 24 apprait deux fois dans le fichier de départ et donc le nombre 2 est renvoyée dans un fichier nommé 24 et ainsi de suite. c'est du tri non????
-
en tout cas j'ai essayé ta methode et ca marche parfaitement voila le code pour ceux que ça intéresse:
public class MaskType { static int mask_count=0; public MaskType(File f) throws FileNotFoundException, IOException { Map< String,Integer> mp=new HashMap <String, Integer>(); InputStream ips=new FileInputStream(f); InputStreamReader ipsr=new InputStreamReader(ips); BufferedReader br=new BufferedReader(ipsr); String ligne=""; while ((ligne=br.readLine())!=null) { // adding or set elements in Map by put method key and value pair if (mp.containsKey(ligne)) { mask_count=mp.get(ligne); mask_count=mask_count+1; mp.put(ligne, mask_count); } else { mp.put(ligne, 1); } } //Get Map in Set interface to get key and value Set s=mp.entrySet(); //Move next key and value of Map by iterator Iterator it=s.iterator(); while(it.hasNext()) { // key=value separator this by Map.Entry to get key and value Map.Entry m =(Map.Entry)it.next(); // getKey is used to get key of Map String key=(String)m.getKey(); // getValue is used to get value of key in Map int value = (int)m.getValue(); FileWriter fw = new FileWriter ("/root/Desktop/"+key); BufferedWriter bw = new BufferedWriter (fw); PrintWriter pr=new PrintWriter(bw); pr.println(value); pr.flush(); System.out.println("Key :"+key+" Value :"+value); } } public static void main(String[] args) throws FileNotFoundException, IOException { MaskType m=new MaskType(new File("/root/Desktop/test")); } }