Rechercher : dans
Par :

Ajout ligne dans un fichier texte en Java

Dernière réponse le 14 jan 2008 à 18:20:35 banbino56, le 14 jan 2008 à 16:15:57 
 Signaler ce message aux modérateurs

Bonjour,

j'ai un soucis en Java. Je dois rechercher dans un texte des mots clés du genre "error(param1,param2,...) ou encore Write(param1,param2,...) et à chaque fois que j'en trouve un, je dois rajouter dans le code un Tag juste avant la ligne trouvée. (ex: ** TAG** méthode(param1,param2...) et ensuite mettre en commentaire la ligne où il y avait le mot clé.

Ca fait un moment que je cherche mais je ne trouve pas la solution. Quelqu'un pourrait m'aider?
Merci d'avance.

Configuration: Windows XP
Firefox 2.0.0.11

Meilleures réponses pour « Ajout ligne dans un fichier texte en Java » dans :
[MS-Dos] Ecrire dans un fichier texte en batch VoirPour écrire dans un fichier texte, il suffit d'utiliser une redirection ">" : echo texte_à_ecrire > fichier_de_sortie.txt Pour écrire à la fin d'un texte existant (concaténation) : echo "écriture a la fin du fichier ">>...
MySQL - Chargement d'un fichier texte dans une table VoirPour charger une fichier texte défini comme suit : $ tail /home/user1/test.txt 'nom1',1,9 'nom2',2,3 'nom3',3,54 'nom4',4,2 'nom5',5,9 Dans une table définie comme suit : CREATE TABLE chargertest ( ...
Fichier TXT VoirFormat TXT Un fichier TXT est un fichier texte, c'est-à-dire un simple fichier contenant du texte au format ASCII. Pour ouvrir ou modifier un tel fichier, il suffit d'utiliser le bloc-notes ou un éditeur de texte traditionnel.

1

 kij_82, le 14 jan 2008 à 18:20:35
  • +2

Bonjour,

Pour trouver l'index (position) d'une chaine de caractère dans une autre tu utilise indexOf.
Ca te retourne un entier (position de départ). Si cet entier vaut -1 c'est que ta chaine n'a pas été trouvée, dans le cas contraire elle a été trouvée.
Dans ce cas, ce qui intéresse est de pouvoir insérer juste avant (et juste après), des balises, autrement dit du texte. Pour cela rien de plus simple, voici un exemple complet (en partant juste de la chaine de caractère)


	public static void FindAndUpdate ( String theInputFileName, String theOutputFileName, String theSymbol, String theCommentSymbol, String theExpression ){
		
		int myStartIndex = -1;
		String myTmpStr	 = null;
		String myOutputString	= "";
		boolean found = false;
		
		RandomAccessFile myInputFile = null;
		RandomAccessFile myOutputFile = null;
		String myLine = null;
		
		try{
			// --- Open the file
			myInputFile = new RandomAccessFile(theInputFileName, "r");
			myOutputFile = new RandomAccessFile(theOutputFileName, "rw");
			
			// --- Read line per line
			while (  (myLine = myInputFile.readLine() ) != null ){
				
				// --- Init the index for the new line
				myStartIndex = -1;
				found = false;
				myOutputString = "";
				
				myTmpStr = myLine;
				// --- And for each line, search the pattern 'theSymbol' and try to comment it
				while ( myTmpStr != "" && (myStartIndex = myTmpStr.indexOf(theSymbol)) != -1 ){
					
					found = true;
					myOutputString = myTmpStr.substring(0, myStartIndex).concat(theExpression).concat( theSymbol );
					myTmpStr = myTmpStr.substring( myStartIndex + theSymbol.length(), myTmpStr.length() );
				}
				
				// --- Add the end of the line
				if ( myTmpStr != "" )
					myOutputString += myTmpStr;
					
				// --- If the tag had been found, comment the line (add '//' at the beginning of the line
				if ( found )
					myOutputString = "\n".concat(theCommentSymbol).concat(myOutputString);
				else
					// --- No symbol found, so just write the same line
					myOutputString = "\n".concat(myLine);
				
				// --- Finally add this new line to the output file
				myOutputFile.write( myOutputString.getBytes());
			}
			
		}catch (IOException e){
			System.err.println("IOException : "+e.getMessage());
		}finally {
			// --- Close the openned files
			try{
				myInputFile.close();
				myOutputFile.close();
			}catch ( Exception e ){
				; // --- Do nothing
			}
		}
	}


Utilisation :
public static void main ( String[] args ){
		
		String myInputFile = "C:\\CAHDD\\test\\exemple.txt";
		String myOutputFile = "C:\\CAHDD\\test\\exemple2.txt";
		String theSymbol = "export(";
		String theCommentSymbol = "//";
		String theTag = "<ICI>";
		
		FindAndUpdate(myInputFile, myOutputFile,theSymbol, theCommentSymbol, theTag);
		
		
	}


Avec dans le fichier texte 'exemple.txt', plusieurs ligne de texte dont certaine contienne l'expression "export(".
C'est un exemple, ca fonctionne, reste plus qu'à l'adapter à tes besoins.

~ N'oubliez pas la balise "Résolu" lorsque votre problème est... résolu :) ~

Répondre à kij_82