I'd just written a java file using Eclipse encoding with ISO-8859-1. In this file, I want to create a String such like that (in order to create a XML content and save it into a database) :
// <image><img src="path_of_picture"></image>
String xmlContent = "<image><img src=\"" + path_of_picture+ "\"></image>";
In another file, I get this String and create a new String with this constructor :
String myNewString = new String(xmlContent.getBytes(), "UTF-8");
In order to be understood by a XML parser, my XML content must be converted to :
<image><img src="path_of_picture"></image>
Unfortunately, I can't find how to write xmlContent to get this result in myNewString. I tried two methods :
// First :
String xmlContent = "<image><img src=\"" + content + "\"></image>";
// But the result is just myNewString = <image><img src="path_of_picture"></image>
// and my XML parser can't get the content of <image/>
//Second :
String xmlContent = "<image><img src=\"" + content + "\"></image>";
// But the result is just myNewString = <image>&lt;img src="path_of_picture"&gt;</image>
Do you have any idea ?
This is unclear. But Strings don't have an encoding. So when you write
String s = new String(someOtherString.getBytes(), someEncoding);
you will get various results depending on your default encoding setting (which is used for the getBytes()
method).
If you want to read a file encoded with ISO-8859-1, you simply do:
byte[] bytes = Files.readAllBytes(path);
String content = new String(bytes, "ISO-8859-1);
If you need to write back the file with a UTF-8 encoding you do:
byte[] utfBytes = content.getBytes("UTF-8");
Files.write(path, utfBytes);
I dont feel that your question is related to encoding but if you want to "create a String such like that (in order to create a XML content and save it into a database)", you can use this code:
public static Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
Refer this SO answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.