Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. private static final Pattern NOT_ASCII = compile("[^\\p{ASCII}]")
  2.  
  3. private static String OS = System.getProperty("os.name").toLowerCase()
  4. /**
  5. * Remove a acentuação do texto.
  6. * @param text Texto com acentuação.
  7. * @return Texto sem acentuação.
  8. */
  9. public static String removeAccents(String text) {
  10. if ((OS.indexOf("win") >= 0)) {
  11. if (!text) {
  12. return text
  13. }
  14. if (isValidUTF8(text.getBytes())) {
  15. try {
  16. Charset utf8charset = Charset.forName("UTF-8");
  17. Charset iso88591charset = Charset.forName("ISO-8859-1");
  18.  
  19. ByteBuffer inputBuffer = ByteBuffer.wrap(text.getBytes());
  20.  
  21. // decode ISO-8559-1
  22. CharBuffer data = utf8charset.decode(inputBuffer);
  23.  
  24. // encode UTF-8
  25. ByteBuffer outputBuffer = iso88591charset.encode(data);
  26. byte[] outputData = outputBuffer.array();
  27.  
  28. text = new String(outputData);
  29. } catch (Exception ignored) {
  30. }
  31. }
  32. String normalized = normalize(text, NFD);
  33.  
  34. return NOT_ASCII.matcher(normalized).replaceAll("");
  35. }
  36. return text;
  37. }
  38.  
  39. public static boolean isValidUTF8(byte[] input) {
  40. try {
  41. Charset.forName("UTF-8").newDecoder().decode(ByteBuffer.wrap(input));
  42. return true;
  43. } catch (CharacterCodingException ignored) {
  44. return false;
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement