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

Entrée/Sortie Java Discussion :

Fermeture de fichier


Sujet :

Entrée/Sortie Java

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    84
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 84
    Points : 69
    Points
    69
    Par défaut Fermeture de fichier
    Bonjour,

    je vais pas rentrer dans les détails de l'application mais a un moment celle ci crée un fichier backup qui ne s'affiche pas au final, si je relance l'appli il se passe un truc etrange... le premier backup apparait et si je le supprime, le deuxieme apparait...

    Un probleme de fermeture certainement ?

    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
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.InputStreamReader;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
     
     
    public class ModiFile {
     
    	public static boolean modiFile(String name)
    	{
    		String xmlline = null;
    		int XMLVers = LectureXML.lectureXML(name);
    		int XSLVers = LectureXSL.lectureXSL(name);
     
    		DateFormat dateFormat = new SimpleDateFormat("dd-MM_");
    		Date actuelle = new Date();
     
    		if (XSLVers<XMLVers)
    		{
    			try{
     
    		    	// Open the file that is the first 
    		    	// command line parameter
    		    	FileInputStream fstream = new FileInputStream("/export/home/rfnetco/rfcfg_xml/switch_export/umts/dbupload/xsl/"+name+".xsl");
     
    				// Get the object of DataInputStream
    		    	DataInputStream in = new DataInputStream(fstream);
    		    	BufferedReader br = new BufferedReader(new InputStreamReader(in));
    		    	String strLine;
     
    		    	// Put version number in string
    		    	String versionstr = (String.valueOf(XMLVers));
    		    	versionstr = versionstr.substring(0, 2)+"."+versionstr.substring(2, 4);
     
    		    	// Go to the 2nd line
    		    	br.readLine();
    		    	strLine = (br.readLine());
    		    	//System.out.println(versionstr);
     
    		    	xmlline = strLine.substring(0, 218)+versionstr+strLine.substring(223, strLine.length());
    		    	//System.out.println(xmlline);
     
    		    //Close the input stream
    		    in.close();
    		    }catch (Exception e){//Catch exception if any
    		      System.err.println("Error reading XSL file : " + e.getMessage());
    		    }
     
    		    try {
     
    				// Create file
    				File backup = new File("/export/home/rfnetco/rfcfg_xml/switch_export/umts/dbupload/xsl/backup"+dateFormat.format(actuelle)+name+".xsl");
     
    				if(backup.exists() == false)
    				{
    					backup.createNewFile();
    				}
     
     
    	            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/export/home/rfnetco/rfcfg_xml/switch_export/umts/dbupload/xsl/"+name+".xsl")));
     
    	            StringBuffer sb = new StringBuffer();
    	            StringBuffer back = new StringBuffer();
     
    	            String line;    
    	            int nbLinesRead = 0;       
    	            while ((line = reader.readLine()) != null) {
    	            	back.append(line + "\n");
    	                if (nbLinesRead != 1) {
    	                    sb.append(line + "\n");
    	                }
    	                else sb.append(xmlline + "\n");
    	                nbLinesRead++;
    	            }
    	            reader.close();
     
    	            BufferedWriter out = new BufferedWriter(new FileWriter("/export/home/rfnetco/rfcfg_xml/switch_export/umts/dbupload/xsl/"+name+".xsl"));
    	            BufferedWriter outback = new BufferedWriter(new FileWriter("/export/home/rfnetco/rfcfg_xml/switch_export/umts/dbupload/xsl/backup"+dateFormat.format(actuelle)+name+".xsl"));
     
    	            outback.write(back.toString());
    	            outback.flush();
    	            outback.close();
     
    	            out.write(sb.toString());
    	            out.flush();
    	            out.close();
     
     
    	            System.out.println("Modification Done and backup name is : backup"+dateFormat.format(actuelle)+name+".xsl");
     
    	        } catch (Exception e) {
    	            return false;
    	        } 
      	  	} else System.out.println("XML/XSL versions already equals for "+name+" file.");
    		return true;
    	}
     
    }
    Merci beaucoup pour votre aide !

  2. #2
    Membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    84
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 84
    Points : 69
    Points
    69
    Par défaut
    Le problème venait pas de mon applet mais d'un problème de rafraichissement de l'environnement dans lequel je travaillais.

  3. #3
    Membre éclairé
    Homme Profil pro
    NoOb
    Inscrit en
    Mai 2007
    Messages
    554
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : NoOb

    Informations forums :
    Inscription : Mai 2007
    Messages : 554
    Points : 852
    Points
    852
    Par défaut
    Bonjour,

    Ton code s’exécute sans erreur?
    Certains de tes catchs n'affichent pas de trace.

    Sinon:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    try {
        ...
    } catch (Exception e) {
        // on affiche la trace, surtout si tu débug et 
        //que tu sais pas d'ou viens le problème.
    } finally {
        // on ferme les buffers / streams / fichiers et autres joyeusetés
    }

  4. #4
    Membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    84
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 84
    Points : 69
    Points
    69
    Par défaut
    Dans mon finally, je met tous mes "close" et "flush" ?

    Ça me donnerait ceci :

    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
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
     
    public class ModiFile {
     
    	public static boolean modiFile(String name) throws IOException {
    		String xmlline = null;
    		int XMLVers = LectureXML.lectureXML(name);
    		int XSLVers = LectureXSL.lectureXSL(name);
     
    		if (XSLVers < XMLVers) {
     
    			DataInputStream in = null;
    			BufferedReader br = null;
     
    			try {
    				// Open the file
    				FileInputStream fstream = new FileInputStream(FilePath.pathXSL(name));
     
    				// Get the object of DataInputStream
    				in = new DataInputStream(fstream);
    				br = new BufferedReader(new InputStreamReader(in));
    				String strLine;
     
    				// Put version number in string
    				String versionstr = (String.valueOf(XMLVers));
    				versionstr = versionstr.substring(0, 2) + "."+ versionstr.substring(2, 4);
     
    				// Go to the 2nd line
    				br.readLine();
    				strLine = (br.readLine());
     
    				xmlline = strLine.substring(0, 218) + versionstr+ strLine.substring(223, strLine.length());
     
    				// Close the input stream
     
     
    			} catch (Exception e) {// Catch exception if any
    				System.err.println("Error reading XSL file : " + e.getMessage());
    			} finally {
    				in.close();
    				br.close();
    			}
     
    			BufferedReader reader = null;
    			BufferedWriter out = null;
    			BufferedWriter outback = null;
     
    			try {
     
    				// Create file
    				File backup = new File(FilePath.pathBackupXSL(name));
     
    				if (backup.exists() == false) {
    					backup.createNewFile();
    				}
     
    				reader = new BufferedReader(new InputStreamReader(new FileInputStream(FilePath.pathXSL(name))));
     
    				StringBuffer sb = new StringBuffer();
    				StringBuffer back = new StringBuffer();
     
    				String line;
    				int nbLinesRead = 0;
     
    				while ((line = reader.readLine()) != null) {
    					back.append(line + "\n");
    					if (nbLinesRead != 1) {
    						sb.append(line + "\n");
    					} else
    						sb.append(xmlline + "\n");
    					nbLinesRead++;
    				}
    				reader.close();
     
    				out = new BufferedWriter(new FileWriter(FilePath.pathXSL(name)));
    				outback = new BufferedWriter(new FileWriter(FilePath.pathBackupXSL(name)));
     
    				outback.write(back.toString());
    				out.write(sb.toString());
     
    				System.out.println("Modification Done and backup name is : "+ FilePath.pathBackupXSL(name));
     
    			} catch (Exception e) {
    				System.err.println("Error Create File / Copy File : "+ e.getMessage());
    			} finally {
     
    				outback.flush();
    				outback.close();
     
    				out.flush();
    				out.close();
    			}
    		} else
    			System.out.println("XML/XSL versions already equals for " + name+ " file.");
    		return true;
    	}
     
    }

  5. #5
    Membre éclairé
    Homme Profil pro
    NoOb
    Inscrit en
    Mai 2007
    Messages
    554
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : NoOb

    Informations forums :
    Inscription : Mai 2007
    Messages : 554
    Points : 852
    Points
    852
    Par défaut
    Que ça tombe dans le catch ou pas, le code qui est dans finally sera toujours appelé, donc c'est bien pour fermer ce qui traîne.

    Je crois que c'est une bonne pratique, sinon un membre expert me tapera sur les doigts!

  6. #6
    Membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    84
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 84
    Points : 69
    Points
    69
    Par défaut
    Merci pour tes bons conseils !

    Faire les choses proprement est toujours plus agréable

  7. #7
    Membre chevronné
    Avatar de Deadpool
    Homme Profil pro
    Inscrit en
    Novembre 2005
    Messages
    1 312
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations forums :
    Inscription : Novembre 2005
    Messages : 1 312
    Points : 2 011
    Points
    2 011
    Par défaut
    A noter que la FAQ Java donne une bonne méthode pour gérer proprement la fermeture des ressources de flux.

    http://java.developpez.com/faq/java/...ererRessources

    -"Tout ça me paraît très mal organisé. Je veux déposer une réclamation. Je paye mes impôts, après tout!"
    -"JE SUIS LA MORT, PAS LES IMPÔTS! MOI, JE N'ARRIVE QU'UNE FOIS".

    Pieds d'argile (1996), Terry Pratchett 1948 - 2015
    (trad. Patrick Couton)

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Lancement et fermeture de fichier exécutable
    Par manue22 dans le forum VB 6 et antérieur
    Réponses: 3
    Dernier message: 19/04/2007, 18h47
  2. Probleme de fermeture de fichier
    Par franc82 dans le forum C++
    Réponses: 1
    Dernier message: 08/11/2006, 17h14
  3. [VBA-E] fermeture de fichier et curseur de souris
    Par thitoux dans le forum Macros et VBA Excel
    Réponses: 4
    Dernier message: 31/08/2006, 13h17
  4. Pb de fermeture de fichiers .js
    Par Cako19 dans le forum Général JavaScript
    Réponses: 5
    Dernier message: 27/12/2005, 15h17
  5. Fermeture de fichier
    Par patmaba dans le forum Entrée/Sortie
    Réponses: 12
    Dernier message: 05/10/2005, 11h00

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