Regex com XML?

52 respostas
E

tem como ler o xml verificar a tag ReferencedEntitlement e verificar [telefone removido] se o numero é final 0038, caso isso seja afirmativo apagar a tag inteira

eu consigo fazer isso com regex

<ReferencedEntitlement id="4504a142-d39c-4af4-8314-62b90feac165">
        <CreationDate>2011-05-20T14:12:31.323Z</CreationDate>
        <ProductId>c856c318-51e1-468a-b950-8bc3ed3e5b89</ProductId>
        <CustomerId>[telefone removido]</CustomerId>
      </ReferencedEntitlement>

obrigado

52 Respostas

L
Acho que você pode tentar fazer isso com Dom4j + XPath para achar o nó e fazer a remoção...
package snippet;

import java.io.IOException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Snippet {

	public static void main(String[] args) throws IOException,
			DocumentException {
		String xml = "<root>" +
				"<ReferencedEntitlement id=\"4504a142-d39c-4af4-8314-62b90feac165\">" +
					"<CreationDate>2011-05-20T14:12:31.323Z</CreationDate>" +
					"<ProductId>c856c318-51e1-468a-b950-8bc3ed3e5b89</ProductId>" +
					"<CustomerId>[telefone removido]</CustomerId>" +
				"</ReferencedEntitlement>" +
				"<ReferencedEntitlement id=\"4504a142-d39c-4af4-8314-62b90feac165\">" +
					"<CreationDate>2011-05-20T14:12:31.323Z</CreationDate>" +
					"<ProductId>c856c318-51e1-468a-b950-8bc3ed3e5b8x</ProductId>" +
					"<CustomerId>485723003x</CustomerId>" +
					"</ReferencedEntitlement>" +
				"</root>";
				

		Document doc = DocumentHelper.parseText(xml);

		for (Element noh : ((List<Element>)doc.selectNodes("//ReferencedEntitlement/CustomerId"))) {
			String texto = noh.getTextTrim();
			System.out.println("Vendo: " + noh.asXML() + "(" + texto + ")");
			if (texto != null && texto.endsWith("0038")) {
				//remove o referenced...
				System.out.println("Removendo " + noh.getParent().asXML());
				noh.getParent().detach();
			}
		}
		
		//o que sobrou:
		System.out.println(doc.asXML());
	}

}
E

olha como estou fazendo

public class Main {
	String caminho = "C:" + File.separator + "Desenvolvimento" + File.separator
			+ "XML" + File.separator + "VODUsage_007099_20110520151501.xml";
	String caminhoModificado = "C:" + File.separator + "Desenvolvimento"
			+ File.separator + "XML" + File.separator
			+ "VODUsage_007099_20110520151501MOD.xml";

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		try {
			new Main().converter();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String retornaValor(Element elem, String tagName) throws Exception {
		NodeList children = elem.getElementsByTagName(tagName);
		if (children == null)
			return null;
		Element child = (Element) children.item(0);
		if (child == null)
			return null;
		return child.getFirstChild().getNodeValue();
	}

	private boolean validarNumero(String numero) {
		Pattern p = Pattern.compile("[0-9]*0038");
		Matcher m = p.matcher(numero);
		return m.matches();

	}

	public void converter() throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(caminho);
		Element raiz = doc.getDocumentElement();
		NodeList listaReference = raiz
				.getElementsByTagName("ReferencedEntitlement");
		int tamanho = listaReference.getLength();

		for (int i = 0; i < tamanho; i++) {
			Element elemento = (Element) listaReference.item(i);
			NodeList n = elemento.getChildNodes();
			for (int x = 0; x < n.getLength(); x++) {
				if (n.item(x).getNodeName().equals("CustomerId")) {
					String numero = retornaValor(elemento, "CustomerId");
					if (validarNumero(numero)) {
						raiz.removeChild(elemento);
					}
				}
			}
		}

		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new FileOutputStream(new File(
				caminhoModificado)));
		TransformerFactory transFactory = TransformerFactory.newInstance();
		Transformer transformer = transFactory.newTransformer();
		transformer.transform(source, result);

	}

}

mais na hora de remover “raiz.removeChild(elemento);”

ele gera a seguinte exceção

org.w3c.dom.DOMException: NOT_FOUND_ERR: An attempt is made to reference a node in a context where it does not exist.
	at com.sun.org.apache.xerces.internal.dom.ParentNode.internalRemoveChild(ParentNode.java:497)
	at com.sun.org.apache.xerces.internal.dom.ParentNode.removeChild(ParentNode.java:478)
	at Main.converter(Main.java:77)
	at Main.main(Main.java:37)
L

Eu não conheço o DOM/XML “padrão” do Java, desculpe. Acho que não poderei te ajudar.

Porém recomendo que você troque para o Dom4J (+ Jaxen, que é a dependência para o XPath funcionar) se possível :slight_smile:

Deixa eu justificar: a biblioteca é bem documentada, vem com vários “selectNodes” que funcionam com XPath. Tem também conversão fácil para e dê Strings. E é uma lib que vem por “padrão” no JBoss, o que facilita o uso quando em servidor de aplicativo.

E

cara não consegui usar seu exemplo ele pede pra fazer um monte de cast

E

eu tenho que add bibliotecas? eu não conheço este, ja aproveitando vc fala //remove o referenced… como eu removo?

L

Isso no Java 6?

Se você quiser, eu posso tentar colocar o projeto Eclipse zipado aqui…

E

pode ser java 6,seria muito bom srs

L

Sim! Dom4j 1.6.1 e Jaxen 1.1.3.

E

se possivel, não for pedir muito, me manda o projeto zipado, ja vem com as bibliotecas ne?

E

dom4j-2.0.0-ALPHA-2 2010-04-05 15.672 downloads
dom4j 2.0 ALPHA 2010-01-25 2.735 downloads
dom4j

qual eu baixo?

L

Vamos ver se o fórum aceita…

L

Tá lá.

E

Muito obrigado por estar me ajudando,

o como eu removo a referencia

//remove o referenced…?

L

É a linha de baixo…

noh.getParent().detach();  //isso remove a referência!
E

então aqui ele recebe

mais no meu caso ele precisa receber um file tem alguma forma

Document doc = DocumentHelper.parseText(FILE);

E

^^

L

O Guia é seu amigo...

Parsing XML One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class Foo {

    public Document parse(URL url) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        return document;
    }
}

Só fazer o read com o File...

Ou usar o CommonsIO para ler tudo pra String...

Document doc = DocumentHelper.parseText(FileUtils.readFileToString(file));
E

fiz assim

public void converter() throws Exception {
		SAXReader reader = new SAXReader();
		File arquivo = new File(caminho);
		Document doc = reader.read(arquivo);
        
        for (Element noh : ((List<Element>)doc.selectNodes("//ReferencedEntitlement/CustomerId"))) {  
            String texto = noh.getTextTrim();  
            System.out.println("Vendo: " + noh.asXML() + "(" + texto + ")");  
            if (texto != null && texto.endsWith("038")) {  
                //remove o referenced...  
                System.out.println("Removendo " + noh.getParent().asXML());  
                noh.getParent().detach();  
            }  
        }  
          
	}

mais ele não entra no for , JA APROVEITANDO o 038 temque ser os ultimos caracteres da seguencia

E

estrutura do xml esta assim

<References>
    <ReferencedEntitlements>
      <ReferencedEntitlement id="sfsdfsdfa5">
        <CreationDate>dfsfsdf</CreationDate>
        <ProductId>sdfsdfsd</ProductId>
        <CustomerId>545645645213038</CustomerId>
      </ReferencedEntitlement>

     <ReferencedEntitlement id="5eb81fd1-985a-4a18-85c1-fc8c0c4dd989">
        <CreationDate>645645654</CreationDate>
        <ProductId>5456566</ProductId>
      </ReferencedEntitlement>

</ReferencedEntitlements>
    <ReferencedAssets>
      <ReferencedAsset id="[telefone removido]">
        <ExternalId>45648245</ExternalId>
        <Titles>
          <Title lang>456od</Title>
        </Titles>
        <IngestSource></IngestSource>
        <ContentProviderId>dlatv.net</ContentProviderId>
        <BillingId>04561</BillingId>
        <ContractName>Robin 464565497</ContractName>
      </ReferencedAsset>
  </References>
</VodUsage>

eu tentei fazer assim root.elementIterator( “//VodUsage/References/ReferencedEntitlements/ReferencedEntitlement/CustomerId”)

mais nada

E

pessoal alguem pode me dar uma ajuda com esse ultimo detalhe?

obrigado

L

Corrigindo o XML para ficar bem-formado, vi que o código funcionou sim... Ele remove o que tem final 038 (o primeiro). Não entendi seu problema?!

XML:
<VodUsage>
	<References>
		<ReferencedEntitlements>
			<ReferencedEntitlement id="sfsdfsdfa5">
				<CreationDate>dfsfsdf</CreationDate>
				<ProductId>sdfsdfsd</ProductId>
				<CustomerId>545645645213038</CustomerId>
			</ReferencedEntitlement>

			<ReferencedEntitlement id="5eb81fd1-985a-4a18-85c1-fc8c0c4dd989">
				<CreationDate>645645654</CreationDate>
				<ProductId>5456566</ProductId>
			</ReferencedEntitlement>

		</ReferencedEntitlements>
		<ReferencedAssets>
			<ReferencedAsset id="[telefone removido]">
				<ExternalId>45648245</ExternalId>
				<Titles>
					<Title>456od</Title>
				</Titles>
				<IngestSource></IngestSource>
				<ContentProviderId>dlatv.net</ContentProviderId>
				<BillingId>04561</BillingId>
				<ContractName>Robin 464565497</ContractName>
			</ReferencedAsset>
		</ReferencedAssets>
	</References>
</VodUsage>
Código (igual a antes, só lendo de arquivo)
SAXReader reader = new SAXReader();
		File arquivo = new File("xml.xml");
		Document doc = reader.read(arquivo);

		for (Element noh : ((List<Element>) doc
				.selectNodes("//ReferencedEntitlement/CustomerId"))) {
			String texto = noh.getTextTrim();
			System.out.println("Vendo: " + noh.asXML() + "(" + texto + ")");
			if (texto != null && texto.endsWith("038")) {
				// remove o referenced...
				System.out.println("Removendo " + noh.getParent().asXML());
				noh.getParent().detach();
			}
		}

		// o que sobrou:
		System.out.println("--------------");
		System.out.println("Sobrou:");
		System.out.println(doc.asXML());
Output do programa:
Vendo: <CustomerId>545645645213038</CustomerId>(545645645213038)
Removendo <ReferencedEntitlement id="sfsdfsdfa5">
				<CreationDate>dfsfsdf</CreationDate>
				<ProductId>sdfsdfsd</ProductId>
				<CustomerId>545645645213038</CustomerId>
			</ReferencedEntitlement>
--------------
Sobrou:
<?xml version="1.0" encoding="UTF-8"?>
<VodUsage>
	<References>
		<ReferencedEntitlements>
			

			<ReferencedEntitlement id="5eb81fd1-985a-4a18-85c1-fc8c0c4dd989">
				<CreationDate>645645654</CreationDate>
				<ProductId>5456566</ProductId>
			</ReferencedEntitlement>

		</ReferencedEntitlements>
		<ReferencedAssets>
			<ReferencedAsset id="[telefone removido]">
				<ExternalId>45648245</ExternalId>
				<Titles>
					<Title>456od</Title>
				</Titles>
				<IngestSource/>
				<ContentProviderId>dlatv.net</ContentProviderId>
				<BillingId>04561</BillingId>
				<ContractName>Robin 464565497</ContractName>
			</ReferencedAsset>
		</ReferencedAssets>
	</References>
</VodUsage>
E

ueh, estou debugando, e o meu não entra no forr…

E

vc testou ai deu certinho?

sera que tem haver com a estrutura do xml?

<?xml version="1.0"?>
<VodUsage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:eee:vodusage:2.0">
  <Period startDate="2011-05-20T14:00:00Z" endDate="2011-05-20T15:00:00Z" />
  <TVodPurchases>

o inico é assim

L

Tem a ver com a estrutura do XML sim. Seu XML tem namespaces, que o Jaxen precisa "saber".

Seguindo o link (achado com [google]dom4j xpath xmlns[/google]), vemos que isso acontece com o jaxen. Tem como resolver também. Fica como abaixo:

SAXReader reader = new SAXReader();
		File arquivo = new File("xml.xml");
		Document doc = reader.read(arquivo);

		Map<String, String> map = new HashMap<String, String>();
		map.put("vodusage", "urn:eee:vodusage:2.0");

		org.jaxen.XPath xpath = new Dom4jXPath(
				"//vodusage:ReferencedEntitlement/vodusage:CustomerId");
		xpath.setNamespaceContext(new SimpleNamespaceContext(map));

		List<Element> nodes = xpath.selectNodes(doc);

		for (Element noh : nodes) {
			String texto = noh.getTextTrim();
			System.out.println("Vendo: " + noh.asXML() + "(" + texto + ")");
			if (texto != null && texto.endsWith("038")) {
				// remove o referenced...
				System.out.println("Removendo " + noh.getParent().asXML());
				noh.getParent().detach();
			}
		}

		// o que sobrou:
		 System.out.println("--------------");
		 System.out.println("Sobrou:");
		 System.out.println(doc.asXML());
Output:
Vendo: <CustomerId xmlns="urn:eee:vodusage:2.0">545645645213038</CustomerId>(545645645213038)
Removendo <ReferencedEntitlement xmlns="urn:eee:vodusage:2.0" id="sfsdfsdfa5">
				<CreationDate>dfsfsdf</CreationDate>
				<ProductId>sdfsdfsd</ProductId>
				<CustomerId>545645645213038</CustomerId>
			</ReferencedEntitlement>
--------------
Sobrou:
<?xml version="1.0" encoding="UTF-8"?>
<VodUsage xmlns="urn:eee:vodusage:2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">   
  <Period startDate="2011-05-20T14:00:00Z" endDate="2011-05-20T15:00:00Z"/>   
  <TVodPurchases>  
	<References>
		<ReferencedEntitlements>
			

			<ReferencedEntitlement id="5eb81fd1-985a-4a18-85c1-fc8c0c4dd989">
				<CreationDate>645645654</CreationDate>
				<ProductId>5456566</ProductId>
			</ReferencedEntitlement>

		</ReferencedEntitlements>
		<ReferencedAssets>
			<ReferencedAsset id="[telefone removido]">
				<ExternalId>45648245</ExternalId>
				<Titles>
					<Title>456od</Title>
				</Titles>
				<IngestSource/>
				<ContentProviderId>dlatv.net</ContentProviderId>
				<BillingId>04561</BillingId>
				<ContractName>Robin 464565497</ContractName>
			</ReferencedAsset>
		</ReferencedAssets>
	</References>
	</TVodPurchases>
</VodUsage>
E

Esse é o cara rsrsrs eu dei uma lida tbm nos links parece estar certo…
mais aparce que esta apagando somente duas

. mais se vc observar a ultima saida do    System.out.println("--------------");

System.out.println(Sobrou:);

System.out.println(doc.asXML());

nao aparece nenhum tag ReferencedEntitlement apaga todos

outra coisa ele não atualiza o arquivo xml né?

E

ah para gravar eu faço assim

File file = new File(caminhoModificado);
   FileWriter out = new FileWriter( caminhoModificado );
   doc.write( out );

unico problema é que ele esta terminado com a tag

</References>

e não com

</References>
L

Ele não atualiza o arquivo, isso você escreve depois que terminar.

Só tem um ReferencedEntitlement que tem CustomerId no XML que você enviou. Esse um está com final 038. Está certo, então. Veja no output que ele deixa o “espaço” aonde ficaria o elemento removido…

L

erickfm8:
ah para gravar eu faço assim

File file = new File(caminhoModificado);
   FileWriter out = new FileWriter( caminhoModificado );
   doc.write( out );

unico problema é que ele esta terminado com a tag

</References>

e não com

</References>

Está rolando um out.flush() e out.close()?

E

Cara de u fhush e funcionou pefeitamente,
Deve ter mexido mtu com isso rsrsrsrs
Se quebro um galhão agora tenho que fazer mais uma modificaçao mais vou fuçar aqui

essa modificação aiii,se vc ja tiver um solução rapida e não for incomado,se não deixa que eu tento aki…

saca essa parte

<TVodPurchases>
    <TVodPurchase id="001">
      <PurchaseDate>45546Z</PurchaseDate>
      <DeviceId>269</DeviceId>
      <EntitlementId>001</EntitlementId>
      <Vat>18</Vat>
      <Currency>BRL</Currency>
      <ListPrice inVat="9.9" exVat="8.39" />
      <PurchasePrice inVat="9.9" exVat="8.39" />
         </TVodPurchase>
   <TVodPurchases>    
    <References>  
        <ReferencedEntitlements>  
         <ReferencedEntitlement id="001">  
                <CreationDate>645645654</CreationDate>  
                <ProductId>5456566</ProductId>  
            </ReferencedEntitlement>  
       </ReferencedEntitlements>

depois que eu removi o 038
verifica o id na mesma tag
<ReferencedEntitlement id=“001” tenho que pegar este id e buscar na tag <TVodPurchase id="001 se for igual remover tbm a tag

Muito Obrigado

E

ou pode ser o

001 que é igual o id da
TVodPurchase id

L

Vou dar as dicas:

  • Para pegar o valor do atributo: .valueOf("@nomeAtributo");
  • Para pegar elementos com um atributo com valor específico: .selectNodes("//TVodPurchase[@id=‘001’]");
    • Vide link do XPath que eu passei antes…
E

O valor .valueOf("@nomeAtributo"); PEGA o id?

ReferencedEntitlement id=“001”

ex:

String id = noh.valueOf("@id");
mais aqui eu estou dentro do CustomerId, eu tenho que criar outro for

deste org.jaxen.XPath xpathCustomer = new Dom4jXPath("//vodusage:ReferencedEntitlement")

porque primeiro eu preciso do id do ReferencedEntitlement

L

Você pode dar .getParent() para pegar o pai do CustomerId, não? Não é desse que você quer?

E

é o pai seria ("//vodusage:ReferencedEntitlement") né ;D

L

Sim, e não :slight_smile:

O pai seria o específico para aquele customer que você está removendo…

O // busca por QUALQUER elemento, em qualquer lugar do XML…

E

rsrs mais se eu dar o getParent() ele me retorna o ReferencedEntitlement né?

Element pai = noh.getParent();

ai para pega id

eu faço

String id = pai.valueOf("@id");

E

ai eu tenho o id

.selectNodes("//TVodPurchase[@id="+id+"]");

antes do ponto qual no eu uso, tenho que criar um?

ficaria assim

L

Para dar o selectNodes, que eu lembre, pode ser qualquer um (todos estão ligados à raiz). Mas se não der certo, coloca no document mesmo.

E

ficaria assim?

Map<String, String> map = new HashMap<String, String>();
		map.put("vodusage", "urn:eventis:vodusage:2.0");
		org.jaxen.XPath xpathCustomer = new Dom4jXPath(
				"//vodusage:ReferencedEntitlement/vodusage:CustomerId");
		xpathCustomer.setNamespaceContext(new SimpleNamespaceContext(map));


		Map<String, String> mapPurchase = new HashMap<String, String>();
		map.put("vodusage", "urn:eventis:vodusage:2.0");
		org.jaxen.XPath xpathPurchase = new Dom4jXPath("//vodusage:TVodPurchase/vodusage:EntitlementId");
		xpathPurchase.setNamespaceContext(new SimpleNamespaceContext(
				mapPurchase));

		List<Element> nodesCustomer = xpathCustomer.selectNodes(doc);
        
		
		for (Element noh : nodesCustomer) {
			String texto = noh.getTextTrim();
			if (texto != null && texto.endsWith("038")) {
				Element pai = noh.getParent();
				String id = pai.valueOf("@id");
				Element purchase = (Element) xpathPurchase.selectNodes("//TVodPurchase[@id='"+id+"']"); 
				purchase.getParent().detach();
				noh.getParent().detach();
			}
		}
L

xpathPurchase não é um element, é?

E

ora que ele chega

Element purchase = (Element) xpathPurchase.selectNodes("//TVodPurchase[@id=’"+id+"’]");

gera essa exceção

E

então pode ser o elemento, é que o id é o mesmo valor do elemento

mais eu tirei

ai fico assim

new Dom4jXPath("//vodusage:TVodPurchase);

L

Cara, é por aí. Sem o XML de base, fica difícil de rodar/testar. Não dá para ficar chutando no vazio.

Você usa ou xpath.selectNodes(doc) ou doc.selectNodes("//xyz");

O resto vai ser em volta disso.

E

entendii…,… eu axo que pode ser a sintaxe errada porque eu coloquei um valor real

Element purchase = (Element) doc.selectNodes("//TVodPurchase[@id=‘4504a142-d39c-4af4-8314-62b90feac165’]");

e mesmo assim deu o mesmo erro [@id=‘valor’]

é assim mesmo

L

org.jaxen.XPath xpathPurchase = new Dom4jXPath("//vodusage:ReferencedEntitlement[@id='5eb81fd1-985a-4a18-85c1-fc8c0c4dd989']"); xpathPurchase.setNamespaceContext(new SimpleNamespaceContext(map)); System.out.println(xpathPurchase.selectNodes(doc));

Funciona.

E

mano la dentro quando eu passo da vai nem com reza rsrs

Map<String, String> map = new HashMap<String, String>();
		map.put("vodusage", "urn:eventis:vodusage:2.0");
		org.jaxen.XPath xpathCustomer = new Dom4jXPath(
				"//vodusage:ReferencedEntitlement/vodusage:CustomerId");
		xpathCustomer.setNamespaceContext(new SimpleNamespaceContext(map));


		Map<String, String> mapPurchase = new HashMap<String, String>();
		mapPurchase .put("vodusage", "urn:eventis:vodusage:2.0");
		org.jaxen.XPath xpathPurchase = new Dom4jXPath("//vodusage:TVodPurchase/vodusage:EntitlementId");
		xpathPurchase.setNamespaceContext(new SimpleNamespaceContext(mapPurchase));

	      
		
		List<Element> nodesCustomer = xpathCustomer.selectNodes(doc);
		List<Element> nodesPurchase =  xpathPurchase.selectNodes(doc);

		for (Element noh : nodesCustomer) {
			String texto = noh.getTextTrim();
			if (texto != null && texto.endsWith("038")) {
				Element pai = noh.getParent();
				String id = pai.valueOf("@id");
				noh.getParent().detach();
				for (Element purchase : nodesPurchase ) {
					String idPurchase = purchase.getTextTrim();
					if (id != null && id.equals(idPurchase))
					purchase.getParent().detach();
				}
			}
		}

ai fiz assim e funciono eu acho rsrs

E

Por enquanto deu certo rsrs qualquer coisa do um alo aqui kkkkkkk zueraa rsrs

Cara o seguinte, muito obrigado valew mesmo…ajudo muitoooo
Comunidade do Guj mtu boaa pra resolver as coisa.

Abração

E

rsrs era obvio que não ia dar tudo certo rsrs o original é assim

<?xml version="1.0"> ele gera <?xml version="1.0" encoding="UTF-8"?>

ai zua todo os acentos

E

Consegui, era o enconding da String , mudei o enconding do eclipse ,e tudo deu certo.,…

Obrigado

E

ainda o enconding… quando exporto o jar, não funciona

L

O que não funciona? Você tá testando o quê contra o quê?

Você pode controlar o encoding de entrada e saída do seu *putStream. Também pode depender do leitor que você está abrindo o XML.

E

RESOLVI fazendo a transformação antes de gravar

private void gravar(byte[] bytes, String caminhoDestino) throws Exception {

		ByteArrayInputStream bstrean = new ByteArrayInputStream(bytes);
		Reader input = new InputStreamReader(bstrean, decoder("Cp1252"));
		Writer output = new OutputStreamWriter(new FileOutputStream(
				caminhoDestino), encoder("UTF-8"));
		char[] buffer = new char[4096];
		int length;

		while ((length = input.read(buffer)) != -1) {
			output.write(buffer, 0, length);
		}

		output.flush();
		output.close();

	}

	private static CharsetDecoder decoder(String encoding) {
		return Charset.forName(encoding).newDecoder()
				.onMalformedInput(CodingErrorAction.REPORT)
				.onUnmappableCharacter(CodingErrorAction.REPORT);
	}

	private static CharsetEncoder encoder(String encoding) {
		return Charset.forName(encoding).newEncoder()
				.onMalformedInput(CodingErrorAction.REPORT)
				.onUnmappableCharacter(CodingErrorAction.REPORT);
	}
Criado 26 de maio de 2011
Ultima resposta 31 de mai. de 2011
Respostas 52
Participantes 2