IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage Java Discussion :

Lire fichier et divers :)


Sujet :

Langage Java

  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2007
    Messages
    64
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2007
    Messages : 64
    Par défaut Lire fichier et divers :)
    Bonsoir tout le monde!
    J'ai une petite question qui me semblne intéressante:
    la voici : )

    Je voudrais créere une interface graphique permettant de gérer des fichiers texte ou autres
    mais avant de m occuper de l interface graphique, je prefere bien tester mon code de base, @savoir sans interface graphique...

    Voici donc le code du lecteur de texte:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
     
    package texteditor;
     
    import java.io.*;
     
    public class TextReader {
    	String path=null;
    	FileReader fr=null;
    	BufferedReader buffer=null;
     
     
    	public TextReader(String path) throws FileNotFoundException{
    		this.path=path;
    		fr=new FileReader(path);
    	}
     
    	public void setPath(String path) throws FileNotFoundException{
    		this.path=path;
    		fr= new FileReader(path);
    		buffer=new BufferedReader(fr);
    	}
     
    	public String getPath(){
    		return this.path;
    	}
     
    	public void seeText() throws IOException{
    		String ligne;
    		buffer=new BufferedReader(fr);
    		System.out.println("Début de la lecture du fichier\n==============================");
    		while((ligne=buffer.readLine())!=null){
    			System.out.print(ligne);
    		}
    		buffer.close();
    		System.out.println("\n\n");
    	}
     
    	public String getText() throws IOException{
    		StringBuffer buff = null;
    		String ligne;
    		buffer=new BufferedReader(fr);
    		System.out.println("");
    		while((ligne=buffer.readLine())!=null){
    			buff.append(ligne);
    		}
    		buffer.close();
    		return buff.toString();
    	}
     
    	public static void main(String args[]) throws IOException,FileNotFoundException{
    		TextReader t=new TextReader("Essai");
    		t.seeText();
    		System.out.println(t.getText());
     
    	}
    }
    L'ennui, c'est que ce code génére une erreur assez génante :d
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    Exception in thread "main" java.io.IOException: Stream closed
    	at sun.nio.cs.StreamDecoder.ensureOpen(StreamDecoder.java:38)
    	at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:153)
    	at java.io.InputStreamReader.read(InputStreamReader.java:167)
    	at java.io.BufferedReader.fill(BufferedReader.java:136)
    	at java.io.BufferedReader.readLine(BufferedReader.java:299)
    	at java.io.BufferedReader.readLine(BufferedReader.java:362)
    	at texteditor.TextReader.getText(TextReader.java:42)
    	at texteditor.TextReader.main(TextReader.java:52)
    Enfin encore une autre question: pour copier un fichier dans un autre en Java, une solution consiste a prendre son contenu et le coller dans un autre fichier?

    Je pensais à la méthode getRuntime avec cp mais cela ne marcherait que suir Linux...

    Enfin(bis), je pense qu'il existe un composant Java qui permette de parcourir les fichiers?



    Merci d avance

  2. #2
    Membre émérite
    Profil pro
    Inscrit en
    Février 2007
    Messages
    572
    Détails du profil
    Informations personnelles :
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations forums :
    Inscription : Février 2007
    Messages : 572
    Par défaut
    1. Quand tu appelles close() sur buffer, tu fermes le stream (fr dans ton cas)
    2. faq
    3. java.io.File, et pour le faire avec une IHM, JFileChooser.

  3. #3
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2007
    Messages
    64
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2007
    Messages : 64
    Par défaut
    Donc comment résoudre le probleme du stream?

    Parce que cela est assez génant

    De plus, j'ai un autre code problématique:
    je cherche à coder la fonction GREP et voici mon code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
     
    import java.io.*;
     
     
    public class Grep {
     
    	String file;
    	String search;
     
     
    	public Grep(String path,String s){
    		this.search=s;
    		this.file=path;
    	}
     
    	int search(){
     
    		try{
    			FileReader flot = new FileReader(file);
    			BufferedReader read = new BufferedReader(flot);
    			String ligne=read.readLine();
    			int ctr=0;
    			while(ligne!=null)
    			{
     
    				if(ligne.matches(".*"+search+".*"))
    				{/*if the line contains the searching */
    					/* thanks to "regex" :d */
    					ctr++;
    					ligne=read.readLine();
    				}/*if*/		       
    				ligne=read.readLine();
     
    			}
    			read.close();
    			flot.close();
     
    			return ctr;
     
     
     
    		}/*try*/
    		catch (IOException e)
    		{
    			System.err.println("Malaise: " + e.getMessage());
    			System.exit(0);
    		}/*catch*/
     
     
    		return 0;
     
    	}/*search*/
     
    	public static void main(String args[]){
     
    		if(args.length<2){
    			System.out.println("Syntax: [file] [search]");
    			System.exit(0);
    		}
     
    		Grep g=new Grep(args[0],args[1]);
    		int nb=g.search();
    		if(nb==0){ 
    			System.out.println("This string doesn't appear " );
    			System.exit(0);
    		}
     
    		if(nb==1){
    			System.out.println("This string appears once " );
    			System.exit(0);
    		}
    		System.out.println("This string appears in  " + nb + " exemplaries " );
     
    	}
     
    }/*grep*/
    Quand je l'appelle sur un fichier du style Bonjour\nBonjour\nBonjour\n
    cela affiche seulement 2 exemplaires ... :'(


    Merci d avance !!!!

    PS: je corrige la sortie attendue, je voudrais que cela compte le nombre d exemplaires dans un fichier d'une séquence saisie [cela simule grep -c]

  4. #4
    Membre émérite
    Profil pro
    Inscrit en
    Février 2007
    Messages
    572
    Détails du profil
    Informations personnelles :
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations forums :
    Inscription : Février 2007
    Messages : 572
    Par défaut
    Pour le stream, soit tu le reouvres a chaque fois, soit tu le fermes quand tu n'en n'a plus besoin.

    Pour le probleme du nombre d'exemplaires, je pense que ca vient du fait que tu appelles 2 fois ligne=read.readLine();, dans le cas ou tu trouves un occurrence (une fois dans le if, une fois apres).

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    while(ligne!=null)
    			{
     
    				if(ligne.matches(".*"+search+".*"))
    				{/*if the line contains the searching */
    					/* thanks to "regex" :d */
    					ctr++;
    					ligne=read.readLine();
    				}/*if*/		       
    				ligne=read.readLine();
     
    			}

  5. #5
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2007
    Messages
    64
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2007
    Messages : 64
    Par défaut
    Citation Envoyé par Sanguko
    Pour le stream, soit tu le reouvres a chaque fois, soit tu le fermes quand tu n'en n'a plus besoin.

    Pour le probleme du nombre d'exemplaires, je pense que ca vient du fait que tu appelles 2 fois ligne=read.readLine();, dans le cas ou tu trouves un occurrence (une fois dans le if, une fois apres).

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    while(ligne!=null)
    			{
     
    				if(ligne.matches(".*"+search+".*"))
    				{/*if the line contains the searching */
    					/* thanks to "regex" :d */
    					ctr++;
    					ligne=read.readLine();
    				}/*if*/		       
    				ligne=read.readLine();
     
    			}
    J'avoue :$

    Voila mon code définitif, et il marche si le mot n'apparait qu'une fois dans la ligne..


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
     
    /*********************************************/
    /**                                         **
     *                                           *
     * Author:   DENY Franck Shacamus             *
     *                                           *
     **                                         **/
    /*********************************************/
     
    package flots;
     
    import java.io.*;
     
     
    public class Grep {
     
    	String file;
    	String search;
     
     
    	public Grep(String path,String s){
    		this.search=s;
    		this.file=path;
    	}
     
    	int search(){
     
    		try{
    			FileReader flot = new FileReader(file);
    			BufferedReader read = new BufferedReader(flot);
    			String ligne;//=read.readLine();
    			int ctr=0;
    			while((ligne=read.readLine())!=null)
    			{
     
    				if(ligne.matches(".*"+search+".*"))
    				{/*if the line contains the searching */
    					/* thanks to "regex" :d */
    					ctr++;
    				}/*if*/		       
     
    			}
    			read.close();
    			flot.close();
     
    			return ctr;
     
     
     
    		}/*try*/
    		catch (IOException e)
    		{
    			System.err.println("Malaise: " + e.getMessage());
    			System.exit(0);
    		}/*catch*/
     
     
    		return 0;
     
    	}/*search*/
     
    	public static void main(String args[]){
     
    		if(args.length<2){
    			System.out.println("Syntax: [file] [search]");
    			System.exit(0);
    		}
     
    		Grep g=new Grep(args[0],args[1]);
    		int nb=g.search();
    		if(nb==0){ 
    			System.out.println("This string doesn't appear " );
    			System.exit(0);
    		}
     
    		if(nb==1){
    			System.out.println("This string appears once " );
    			System.exit(0);
    		}
    		System.out.println("This string appears in  " + nb + " exemplaries " );
     
    	}
     
    }/*grep*/
    Serait ce possible de l'améliorer afin de trouver exactement le nombre d occurrences dans le fichier?
    Je pensais tout simplement créer un Scanner qui verifie si chaque mot est ou non une occurrence du terme à chercher...

    Voila, merci d avance pour votre aide!


    EDIT:
    J 'aurais une autre question (jen profite
    Voila: je souhaite créer une interface graphique pour editer des fichiers en Java, et je voudrais une interface du genre
    3/4 de la GUI pour le fichier texte, le reste à droite...
    avec les 3/4 de la GUI étant de type JTextField

    Quel layout utiliser ?
    merci d avance!


    Pour le moment j'ai cela

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
     
    package texteditor;
     
     
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.*;
     
    public class GraphVersion extends JFrame implements ActionListener{
    	/**
             * 
             */
    	private static final long serialVersionUID = 1L;
    	private JPanel container = null;//Declaration de l objet JPanel	
     
    	//Composants 
    	private JButton valider= null ;
    	private JTextField texte= null;
     
    	public GraphVersion(){
    		super();
     
    		build();
    	}
     
    	public static void main(String[] args){
    		GraphVersion g = new GraphVersion();
    		g.setVisible(true);
    	}
     
    	private void build(){
    		this.setTitle("TextEditor"); //On donne un titre � l�application
    		this.setSize(300,200); //On donne une taille � notre fen�tre
    		this.setLocationRelativeTo(null); //On centre la fen�tre sur l��cran
    		this.setContentPane(getContainer()) ;//On lui dit de mettre le panel en fond
    		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    			//On dit � l�application de se fermer lors du clic sur la croix
    	}
     
     
     
    	private JPanel getContainer(){
    		//layout = new SpringLayout() ; //Instanciation du layout
     
    		container = new JPanel() ; //On cr�e notre objet
    		//container.setLayout(layout);
     
    		texte= new JTextField("Fichier",15);
    		container.add(texte);
     
     
     
    		valider= new JButton("Action");
    		valider.setSize(75,75);
    		valider.setLocation(300,200);
    		valider.addActionListener(this);
    		container.add(valider);
     
     
    		return container ;
    	}
     
    	public void actionPerformed(ActionEvent e){
    		if(e.getSource()==valider){
    			texte.setText("Vous avez cliqué!");
    		}
    	}
    }




    EDIT²/
    J'ai tenté d appliquer votre méthode sur les flots mais ca semble toujours pas marcher...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
     
    package texteditor;
     
    import java.io.*;
     
    public class TextReader {
    	String path=null;
    	FileReader fr=null;
    	BufferedReader buffer;
     
     
    	public TextReader(String path) throws FileNotFoundException{
    		this.path=path;
    		fr=new FileReader(path);
    	}
     
    	public void setPath(String path) throws FileNotFoundException{
    		this.path=path;
    		fr= new FileReader(path);
    	}
     
    	public String getPath(){
    		return this.path;
    	}
     
    	public void openBuffer(){
    		buffer=new BufferedReader(fr);
    	}
     
    	public void closeBuffer() throws IOException{
    		buffer.close();
    	}
     
    	public void seeText() throws IOException{
    		String ligne;
    		openBuffer();
    		System.out.println("Début de la lecture du fichier\n==============================");
    		while((ligne=buffer.readLine())!=null){
    			System.out.print(ligne);
    		}
    		System.out.println("\n\n");
    		closeBuffer();
    	}
     
    	public String getText() throws IOException{
    		String l;
    		openBuffer();
    		StringBuffer buff=new StringBuffer();
    		buff=null;
    		System.out.println("Réouverture");
    		while( (l=buffer.readLine() )!=null){
    			buff.append(l);
    		}
     
    		return  buff.toString();
    	}
     
    	public static void main(String args[]) throws IOException,FileNotFoundException{
    		TextReader t=new TextReader("Essai");
    		t.seeText();
    		System.out.println("Res"+t.getText());
    	}
    }
    Lancant cela
    Début de la lecture du fichier
    ==============================
    Bonjour, je suis un fichier à lire


    Réouverture
    Exception in thread "main" java.io.IOException: Stream closed
    at sun.nio.cs.StreamDecoder.ensureOpen(StreamDecoder.java:38)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:153)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    at texteditor.TextReader.getText(TextReader.java:50)
    at texteditor.TextReader.main(TextReader.java:60)

  6. #6
    Membre Expert
    Avatar de afrikha
    Profil pro
    Étudiant
    Inscrit en
    Août 2005
    Messages
    1 600
    Détails du profil
    Informations personnelles :
    Localisation : France, Hauts de Seine (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Août 2005
    Messages : 1 600
    Par défaut
    Salut,

    Quand tu fermes le BufferedReader, le FileReader qui lui est associé est également fermé ! . Donc après l'exécution de la méthode seeText, le FileReader est fermé et par suite la méthode seeText() ne peut pas s'excuter !

    Autre remarque : Dans ta méthode getText() tu crées un StringBuffer pour ensuite lui affecter null

    @+


    Mes publications
    Lisez
    Les régles du forum
    Pensez au bouton

Discussions similaires

  1. Lire fichier suivant son extension !!
    Par Shandler dans le forum Langage
    Réponses: 37
    Dernier message: 18/11/2005, 14h44
  2. [W3C] Lire fichier *.mid sans plugin midi ?
    Par Lareine dans le forum Balisage (X)HTML et validation W3C
    Réponses: 12
    Dernier message: 14/11/2005, 13h23
  3. lire fichier word
    Par benoit70 dans le forum VBA Word
    Réponses: 2
    Dernier message: 26/09/2005, 09h11
  4. Réponses: 2
    Dernier message: 11/09/2005, 05h25

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo