web-dev-qa-db-fra.com

Encoder la chaîne en UTF-8

J'ai une chaîne avec un caractère "ñ" et j'ai quelques problèmes avec elle. J'ai besoin d'encoder cette chaîne en UTF-8. J'ai essayé de cette façon, mais ça ne marche pas:

byte ptext[] = myString.getBytes();
String value = new String(ptext, "UTF-8");

Comment puis-je encoder cette chaîne en utf-8?

169
Alex

Les objets String de Java utilisent le codage UTF-16 qui ne peut pas être modifié.

La seule chose qui peut avoir un encodage différent est un byte[]. Donc, si vous avez besoin de données UTF-8, vous avez besoin d’un byte[]. Si vous avez un String contenant des données inattendues, le problème vient d'un endroit antérieur qui a incorrectement converti certaines données binaires en un String (c'est-à-dire qu'il utilisait un codage incorrect).

128
Joachim Sauer

Comment utiliser

ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(myString)
162
Amir Rachum

Utilisez byte[] ptext = String.getBytes("UTF-8"); au lieu de getBytes(). getBytes() utilise le "codage par défaut", qui peut ne pas être UTF-8.

69
Peter Štibraný

En Java7, vous pouvez utiliser:

import static Java.nio.charset.StandardCharsets.*;

byte[] ptext = myString.getBytes(ISO_8859_1); 
String value = new String(ptext, UTF_8); 

Cela a l'avantage sur getBytes(String) de ne pas déclarer throws UnsupportedEncodingException.

Si vous utilisez une ancienne version Java, vous pouvez déclarer vous-même les constantes du jeu de caractères:

import Java.nio.charset.Charset;

public class StandardCharsets {
    public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
    public static final Charset UTF_8 = Charset.forName("UTF-8");
    //....
}
69
rzymek

Une chaîne Java est toujours codée en interne en UTF-16 - mais vous devriez vraiment y penser comme ceci: un codage est un moyen de traduire entre chaînes et octets.

Donc, si vous avez un problème d'encodage, au moment où vous avez String, il est trop tard pour y remédier. Vous devez corriger l'emplacement où vous créez cette chaîne à partir d'un fichier, d'une base de données ou d'une connexion réseau.

31
Michael Borgwardt

Vous pouvez essayer de cette façon.

byte ptext[] = myString.getBytes("ISO-8859-1"); 
String value = new String(ptext, "UTF-8"); 
23
user716840
String value = new String(myString.getBytes("UTF-8"));

et, si vous voulez lire un fichier texte avec "ISO-8859-1" codé:

String line;
String f = "C:\\MyPath\\MyFile.txt";
try {
    BufferedReader br = Files.newBufferedReader(Paths.get(f), Charset.forName("ISO-8859-1"));
    while ((line = br.readLine()) != null) {
        System.out.println(new String(line.getBytes("UTF-8")));
    }
} catch (IOException ex) {
    //...
}
9
fedesanp

En un instant, je suis passé par ce problème et j'ai réussi à le résoudre de la manière suivante

d'abord, j'ai besoin d'importer

import Java.nio.charset.Charset;

Ensuite, j'ai dû déclarer une constante pour utiliser UTF-8 et ISO-8859-1

private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Charset ISO = Charset.forName("ISO-8859-1");

Ensuite, je pourrais l'utiliser de la manière suivante:

String textwithaccent="Thís ís a text with accent";
String textwithletter="Ñandú";

text1 = new String(textwithaccent.getBytes(ISO), UTF_8);
text2 = new String(textwithletter.getBytes(ISO),UTF_8);
7
Quimbo

J'ai utiliser le code ci-dessous pour coder le caractère spécial en spécifiant le format de codage.

String text = "This is an example é";
byte[] byteText = text.getBytes(Charset.forName("UTF-8"));
//To get original string from byte.
String originalString= new String(byteText , "UTF-8");
3
laxman954

Cela a résolu mon problème

    String inputText = "some text with escaped chars"
    InputStream is = new ByteArrayInputStream(inputText.getBytes("UTF-8"));
0
Prasanth RJ