1 19 20 package org.netbeans.modules.xml.multiview; 21 22 import org.netbeans.modules.xml.api.EncodingUtil; 23 24 import javax.swing.text.StyledDocument ; 25 import java.io.UnsupportedEncodingException ; 26 import java.io.IOException ; 27 import java.io.InputStream ; 28 import java.io.ByteArrayInputStream ; 29 30 33 public class EncodingHelper { 34 public static final String DEFAULT_ENCODING = "UTF-8"; 36 private String encoding = DEFAULT_ENCODING; 37 38 public boolean isValidEncoding(String encoding) { 39 try { 41 new java.io.OutputStreamWriter (new java.io.ByteArrayOutputStream (1), encoding); 42 return true; 43 } catch (UnsupportedEncodingException e) { 44 return false; 45 } 46 } 47 48 public String setDefaultEncoding(String s) { 49 if (s.startsWith("<?xml")) { 51 int i = s.indexOf("?>"); 52 if (i > 0) { 53 s = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + s.substring(i + 2); 54 } 55 } 56 return s; 57 } 58 59 public String getEncoding() { 60 return encoding; 61 } 62 63 public void resetEncoding() { 64 encoding = DEFAULT_ENCODING; 65 } 66 67 public String detectEncoding(StyledDocument document) throws IOException { 68 return setEncoding(EncodingUtil.detectEncoding(document)); 69 } 70 71 public String detectEncoding(InputStream inputStream) throws IOException { 72 return setEncoding(EncodingUtil.detectEncoding(inputStream)); 73 } 74 75 public String detectEncoding(byte[] data) throws IOException { 76 return detectEncoding(new ByteArrayInputStream (data)); 77 } 78 79 public String setEncoding(String encoding) { 80 if (encoding == null) { 81 return this.encoding; 82 } 83 if (isValidEncoding(encoding)) { 84 this.encoding = encoding; 85 } 86 return encoding; 87 } 88 } 89 | Popular Tags |