Conversions de type vers un autre type Java

Conversion integer vers boolean

b = (i != 0);

Conversion boolean vers integer

i = (b)?1:0;

Conversion String vers int

Vous pouvez convertir une String en entier (int) en utilisant la méthode parseInt() de la classe Integer ou en utilisant les méthodes valueOf() et intValue() tel que ci dessous. Dans tous les cas n'oubliez pas de catcher votre conversion avec NumberFormatException si votre String ne contient pas d'entier valide à analyser (parser).

String myStringWithIntValue = "ba34T";
		int myInt = 0;
		try {
//			methode 1 : 
			myInt = Integer.valueOf(myStringWithIntValue).intValue();	// java.lang.NumberFormatException: For input string: "ba34T"
//			ou methode 2 : 
			myInt = Integer.parseInt(myStringWithIntValue);	// java.lang.NumberFormatException: For input string: "ba34T"
			System.out.println(myInt);
		} catch (NumberFormatException e) {
			e.printStackTrace();
//			java.lang.NumberFormatException: For input string: "ba34T"
		}

Convertir un String en InputStream

String s = "maChaine";
InputStream stream = new ByteArrayInputStream(s.getBytes());

Les String et leurs caractères spéciaux

Supprimer les caractères spéciaux

Avec char et Character

En convertissant votre String en Character, on peut utiliser isLetterOrDigit, mais il considère bien les accent comme une "Letter", mais pas les "." par exemple, ce qui peut gêner si l'on traite le nom d'un fichier.

String nomFichier = "Nouveau Documenté texte#ER.txt";
		char[] car = nomFichier.toCharArray(); 
		System.out.println(car);
 
		for(int i=0;i<car.length;i++) {
			System.out.print(car[i]);
 
			Character character = (Character) car[i];
			System.out.println(character.isLetterOrDigit(character));	// prends les accents, mais pas les " ", ".", "#"
 
		}
Avec les expressions régulières (regex)

Avec un pattern de type mot "[^a-zA-Z_.0-9]" ou "\\W" cela supprime les accents.

Predefined character classes
. 	Any character (may or may not match line terminators)
\d 	A digit: [0-9]
\D 	A non-digit: [^0-9]
\s 	A whitespace character: [ \t\n\x0B\f\r]
\S 	A non-whitespace character: [^\s]
\w 	A word character: [a-zA-Z_0-9]
\W 	A non-word character: [^\w]

Il faut donc utiliser le pattern en unicode :

Classes for Unicode blocks and categories
[\p{L}&&[^\p{Lu}]]  	Any letter except an uppercase letter (subtraction)
Categories may be specified with the optional prefix Is: Both \p{L} and \p{IsL} denote the category of Unicode letters. Blocks and categories can be used both inside and outside of a character class. 

Egalement, vous pouvez consulter l'ancien article : Regular Expressions and the Java Programming Language

String in = "Éventuellement le cœur arrête de battre qui il voit les caractères spéciaux, tels que ceux refusés par Windows dans les noms de fichier ; dont la liste est \\ / : * ? \" < > | mais on peut trouver pire : ‘“()!\"#%&'*+,-./;<=>?@[\\]^_`{|}~¢£¤¥¦§¨©ª«²´µ»ÀÁÂÃÄÅƈФ$.";
		String patternIn = "[^\\p{L}0-9(\\,\\-\\w\\.\\s\\')]";
 
		Pattern pattern = Pattern.compile(patternIn);
		Matcher matcher = pattern.matcher(in);
 
		System.out.println("Que trouve le pattern : " +
				patternIn + "\n" +
				"dans la chaine : \n" + 
				in);
 
		String out = matcher.replaceAll("X");
		System.out.println(out);
 
//Que trouve le pattern : [^\p{L}0-9(\,\-\w\.\s\')]
//dans la chaine : 
//Éventuellement le cœur arrête de battre qui il voit les caractères spéciaux, tels que ceux refusés par Windows dans les noms de fichier ; dont la liste est \ / : * ? " < > | mais on peut trouver pire : ‘“()!"#%&'*+,-./;<=>?@[\]^_`{|}~¢£¤¥¦§¨©ª«²´µ»ÀÁÂÃÄÅƈФ$.
//Éventuellement le cœur arrête de battre qui il voit les caractères spéciaux, tels que ceux refusés par Windows dans les noms de fichier X dont la liste est X X X X X X X X X mais on peut trouver pire X XX()XXXXX'XX,-.XXXXXXXXXXX_XXXXXXXXXXXXXªXXXµXÀÁÂÃÄÅƈФX.

Les Collections : Map (HashMap,TreeMap) Set (HashSet,TreeSet) List (ArrayList,LinkedList)

Dans sont très connu Développons en Java, Jean-Michel DOUDOUX explique les collections :

Les interfaces à utiliser par des objets qui gèrent des collections sont :

  • Collection : interface qui est implementée par la plupart des objets qui gèrent des collections
  • Map : interface qui définit des méthodes pour des objets qui gèrent des collections sous la forme clé/valeur
  • Set : interface pour des objets qui n'autorisent pas la gestion des doublons dans l'ensemble
  • List : interface pour des objets qui autorisent la gestion des doublons et un accès direct à un élément
  • SortedSet : interface qui étend l'interface Set et permet d'ordonner l'ensemble
  • SortedMap : interface qui étend l'interface Map et permet d'ordonner l'ensemble

Le framework propose plusieurs objets qui implémentent ces interfaces et qui peuvent être directement utilisés :

  • HashSet : HashTable qui implémente l'interface Set
  • TreeSet : arbre qui implémente l'interface SortedSet
  • ArrayList : tableau dynamique qui implémente l'interface List
  • LinkedList : liste doublement chaînée (parcours de la liste dans les deux sens) qui implémente l'interface List
  • HashMap : HashTable qui implémente l'interface Map
  • TreeMap : arbre qui implémente l'interface SortedMap

D'autres explications sur les collections :

Les dates et les SimpleDateFormat

Lire une date au format attendu depuis une String

public static void testDateFormat() {
 
//		String datePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
		String datePattern = "yyyy-MM-dd'T'HH:mm:ss";
		String dateString = "2009-04-09T09:30:00";
 
		SimpleDateFormat sdfJourTHeure = new SimpleDateFormat(datePattern);		
//		Format ISO 8601:
//		[-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
//		http://java.sun.com/javase/7/docs/api/java/text/SimpleDateFormat.html#rfc822timezone
 
		System.out.println("DateString:"+dateString+" DatePattern:"+datePattern);
		try  {
			Date date = sdfJourTHeure.parse(dateString);			
			System.out.println("Date:"+date);			
		} catch (ParseException e) {
			e.printStackTrace();
		}
 
 
	}
DateString:2009-04-09T09:30:00 DatePattern:yyyy-MM-dd'T'HH:mm:ss.SSSZ
java.text.ParseException: Unparseable date: "2009-04-09T09:30:00"
DateString:2009-04-09T09:30:00 DatePattern:yyyy-MM-dd'T'HH:mm:ss
Date:Thu Apr 09 09:30:00 CEST 2009

Au sujet des dates, regardez l'ISO 8601 sur :

Et pour le SimpleDateFormat :

Les DateFormat (simplistes)

Egalement au lieu de configurer le pattern, on peut utiliser des pré-fabriqués : DateFormat

String datePattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
		SimpleDateFormat sdfJourTHeure = new SimpleDateFormat(datePattern);
 
		System.out.println(date);
		System.out.println(sdfJourTHeure.format(date));
 
		try {
			System.out.print(StringUtils.rightPad("AM_PM_FIELD", wrapLength));
			df = DateFormat.getDateInstance(DateFormat.AM_PM_FIELD, Locale.FRANCE);
//			df = DateFormat.getTimeInstance(DateFormat.AM_PM_FIELD, Locale.FRANCE);
			System.out.println(df.format(date));
		} catch (Exception e) {
			System.out.println("Exception:"  + e.getMessage());
		}
 
/*
 
-----------  DateFormat.getDateInstance(DateFormat.XXX, Locale.FRANCE);
 
Fri Feb 01 07:08:09 CET 2013
2013-02-01T07:08:09.000+0100
AM_PM_FIELD                   Exception:Illegal date style 14
DATE_FIELD                    01/02/13
DAY_OF_WEEK_FIELD             Exception:Illegal date style 9
DAY_OF_WEEK_IN_MONTH_FIELD    Exception:Illegal date style 11
DAY_OF_YEAR_FIELD             Exception:Illegal date style 10
DEFAULT                       1 févr. 2013
ERA_FIELD                     vendredi 1 février 2013
FULL                          vendredi 1 février 2013
HOUR0_FIELD                   Exception:Illegal date style 16
HOUR1_FIELD                   Exception:Illegal date style 15
HOUR_OF_DAY0_FIELD            Exception:Illegal date style 5
HOUR_OF_DAY1_FIELD            Exception:Illegal date style 4
LONG                          1 février 2013
MEDIUM                        1 févr. 2013
MILLISECOND_FIELD             Exception:Illegal date style 8
MINUTE_FIELD                  Exception:Illegal date style 6
MONTH_FIELD                   1 févr. 2013
SECOND_FIELD                  Exception:Illegal date style 7
SHORT                         01/02/13
TIMEZONE_FIELD                Exception:Illegal date style 17
WEEK_OF_MONTH_FIELD           Exception:Illegal date style 13
WEEK_OF_YEAR_FIELD            Exception:Illegal date style 12
YEAR_FIELD                    1 février 2013
 
-----------
 
Tue Dec 24 21:22:23 CET 2013
2013-12-24T21:22:23.000+0100
AM_PM_FIELD                   Exception:Illegal date style 14
DATE_FIELD                    24/12/13
DAY_OF_WEEK_FIELD             Exception:Illegal date style 9
DAY_OF_WEEK_IN_MONTH_FIELD    Exception:Illegal date style 11
DAY_OF_YEAR_FIELD             Exception:Illegal date style 10
DEFAULT                       24 déc. 2013
ERA_FIELD                     mardi 24 décembre 2013
FULL                          mardi 24 décembre 2013
HOUR0_FIELD                   Exception:Illegal date style 16
HOUR1_FIELD                   Exception:Illegal date style 15
HOUR_OF_DAY0_FIELD            Exception:Illegal date style 5
HOUR_OF_DAY1_FIELD            Exception:Illegal date style 4
LONG                          24 décembre 2013
MEDIUM                        24 déc. 2013
MILLISECOND_FIELD             Exception:Illegal date style 8
MINUTE_FIELD                  Exception:Illegal date style 6
MONTH_FIELD                   24 déc. 2013
SECOND_FIELD                  Exception:Illegal date style 7
SHORT                         24/12/13
TIMEZONE_FIELD                Exception:Illegal date style 17
WEEK_OF_MONTH_FIELD           Exception:Illegal date style 13
WEEK_OF_YEAR_FIELD            Exception:Illegal date style 12
YEAR_FIELD                    24 décembre 2013
 
-----------  DateFormat.getTimeInstance(DateFormat.XXX, Locale.FRANCE);
 
Wed Jul 03 05:05:06 CEST 2013
2013-07-03T05:05:06.000+0200
AM_PM_FIELD                   Exception:Illegal time style 14
DATE_FIELD                    05:05
DAY_OF_WEEK_FIELD             Exception:Illegal time style 9
DAY_OF_WEEK_IN_MONTH_FIELD    Exception:Illegal time style 11
DAY_OF_YEAR_FIELD             Exception:Illegal time style 10
DEFAULT                       05:05:06
ERA_FIELD                     05 h 05 CEST
FULL                          05 h 05 CEST
HOUR0_FIELD                   Exception:Illegal time style 16
HOUR1_FIELD                   Exception:Illegal time style 15
HOUR_OF_DAY0_FIELD            Exception:Illegal time style 5
HOUR_OF_DAY1_FIELD            Exception:Illegal time style 4
LONG                          05:05:06 CEST
MEDIUM                        05:05:06
MILLISECOND_FIELD             Exception:Illegal time style 8
MINUTE_FIELD                  Exception:Illegal time style 6
MONTH_FIELD                   05:05:06
SECOND_FIELD                  Exception:Illegal time style 7
SHORT                         05:05
TIMEZONE_FIELD                Exception:Illegal time style 17
WEEK_OF_MONTH_FIELD           Exception:Illegal time style 13
WEEK_OF_YEAR_FIELD            Exception:Illegal time style 12
YEAR_FIELD                    05:05:06 CEST
 
-----------
 
Tue Dec 24 21:22:23 CET 2013
2013-12-24T21:22:23.000+0100
AM_PM_FIELD                   Exception:Illegal time style 14
DATE_FIELD                    21:22
DAY_OF_WEEK_FIELD             Exception:Illegal time style 9
DAY_OF_WEEK_IN_MONTH_FIELD    Exception:Illegal time style 11
DAY_OF_YEAR_FIELD             Exception:Illegal time style 10
DEFAULT                       21:22:23
ERA_FIELD                     21 h 22 CET
FULL                          21 h 22 CET
HOUR0_FIELD                   Exception:Illegal time style 16
HOUR1_FIELD                   Exception:Illegal time style 15
HOUR_OF_DAY0_FIELD            Exception:Illegal time style 5
HOUR_OF_DAY1_FIELD            Exception:Illegal time style 4
LONG                          21:22:23 CET
MEDIUM                        21:22:23
MILLISECOND_FIELD             Exception:Illegal time style 8
MINUTE_FIELD                  Exception:Illegal time style 6
MONTH_FIELD                   21:22:23
SECOND_FIELD                  Exception:Illegal time style 7
SHORT                         21:22
TIMEZONE_FIELD                Exception:Illegal time style 17
WEEK_OF_MONTH_FIELD           Exception:Illegal time style 13
WEEK_OF_YEAR_FIELD            Exception:Illegal time style 12
YEAR_FIELD                    21:22:23 CET
 
*/

Sleep Java => Thread.sleep()

Thread.sleep() est une méthode statique qui met le thread en cours en sommeil. 1 sec... 1000 milli-seconds

join split JAVA comme en PHP

La méthode join() de la classe Joiner du projet Google Collections Library

Joiner joiner = Joiner.on("; ").skipNulls();
   return joiner.join("Harry", null, "Ron", "Hermione");

This returns the string "Harry; Ron; Hermione".

Les méthodes Split et Join de la classe StringUtils du projet Apache Commons Lang

Split/Join - splits a String into an array of substrings and vice versa

Join in Java

This will also work correctly, if the Collection has nulls, or does not implements the protocol correctly.

public static <T>
String join(final Collection<T> objs, final String delimiter) {
    if (objs == null || objs.isEmpty())
        return "";
    Iterator<T> iter = objs.iterator();
    // remove the following two lines, if you expect the Collection will behave well
    if (!iter.hasNext())
        return "";
    StringBuffer buffer = new StringBuffer(String.valueOf(iter.next()));
    while (iter.hasNext())
        buffer.append(delimiter).append(String.valueOf(iter.next()));
    return buffer.toString();
}

Also it could be implemented on Iterables, not just Collections

public static <T>
String join(final Iterable<T> objs, final String delimiter) {
    Iterator<T> iter = objs.iterator();
    if (!iter.hasNext())
        return "";
    StringBuffer buffer = new StringBuffer(String.valueOf(iter.next()));
    while (iter.hasNext())
        buffer.append(delimiter).append(String.valueOf(iter.next()));
    return buffer.toString();
}

Equivalent to PHP split and join

public static String join( String token, String[] strings )
    {
        StringBuffer sb = new StringBuffer();
 
        for( int x = 0; x < ( strings.length - 1 ); x++ )
        {
            sb.append( strings[x] );
            sb.append( token );
        }
        sb.append( strings[ strings.length - 1 ] );
 
        return( sb.toString() );
    }

Encodage

Compiler sous linux en UTF-8 avec Eclipse et obtenir un charset CP1252 sous windows ?

En fait le problème vient du fait que sous Windows la console n'utilise pas vraiment du cp1252 mais du cp850 (enfin sur les Windows français en tout cas). Or Java utilise l'encage par défaut du système et encode tout en cp1252 qui est incompatible avec le cp850... Essayes de vérifier cela en utilisant le paramètre -Dfile.encoding=cp850 pour forcer l'utilisation du cp850.

XML SAX Xerces

Exception.getStackTrace();

Tiré de Java get Stack Trace as String, voici comment enregistrer le contenu d'une Exception au lieu de l'afficher avec e.printStackTrace()

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
 
public class GetStackTraceAsString {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
	    final Throwable throwable = new IllegalArgumentException("Hello");
	    System.out.println( getStackTrace(throwable) );
	}
 
	public static String getStackTrace(Throwable throwable) {
	    Writer writer = new StringWriter();
	    PrintWriter printWriter = new PrintWriter(writer);
	    throwable.printStackTrace(printWriter);
	    return writer.toString();
    }	
 
}

Ressources

  • jtips.info : créé par des consultants en technologies objet, spécialistes de java, ce site recueille les informations techniques rassemblées au cours de leurs missions, sous forme de bloc-note.
  • java-tips.org Java Tips : Java SE Tips, Java ME Tips, Java EE Tips, etc...
  • FAQs JAVA sur developpez.com
  • Programmation Java sur fr.wikibooks.org
  • Annuaire de /tip/java/ sur fileformat.info