Copying an XML document into a String Variable in Java
I am trying to copy an entire XML document, tagnames/tagtypes irrelavant, into a String varible. Language to be used is Java. I used ReadAllTex开发者_如何学编程t to do it in C#, but I need to find an equivalent of that command in Java or another idea to be able to have the entire XML document as a String. I have been working on this for a while now. This is part of a bigger project. This is the only thing that is left to be done. Any suggestions? Thanks in Advance.
Well since this is java and not a scripting language, you will just need to use a scanner or file reader and read it line by line and append it into a single string.
This website has a great overview of file io in java. I actually learned a lot even after knowing about file io.
Here is a sample of what you could do:
private void processFile(File file)
{
StringBuilder allText = new StringBuilder();
String line;
Scanner reader = null;
try {
FileInputStream fis = new FileInputStream(propertyFile);
InputStreamReader in = new InputStreamReader(fis, "ISO-8859-1");
reader = new Scanner(in);
while(reader.hasNextLine() && !errorState)
{
line = reader.nextLine();
allText.append(line);
}
} catch (FileNotFoundException e)
{
System.err.println("Unable to read file");
errorState=true;
} catch (UnsupportedEncodingException e) {
System.err.println("Encoding not supported");
errorState=true;
}
finally
{
reader.close();
}
}
Try following code:
public String convertXMLFileToString(String fileName)
{
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
InputStream inputStream = new FileInputStream(new File(fileName));
org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
StringWriter stw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(doc), new StreamResult(stw));
return stw.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
use an StringWriter
with a StreamResult
.
note, be very careful what you do with that string after that. if you later write it to a stream/byte[] of some sort using the wrong character encoding, you will generate broken xml data.
I used a buffered Reader the last time I did this. Worked well.
String output = "";
try {
FileInputStream is = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = br.readLine()) != null) {
output = output + line;
}
br.close();
is.close();
} catch(IOException ex) {
//LOG!
}
My original implementation was to use an actual buffer but I seemed to keep having issues with flushing the buffer so I went this way which is super easy.
Many answers that get it almost, but not quite, correct.
- If you use a BufferedInputStream and read lines, the result is missing line breaks
- If you use a BufferedReader or a Scanner and read lines, the result is missing the original line breaks an the encoding may be wrong.
- If you use a Writer in a Result, the encoding may not match the source
If you positively know the source encoding, you can do this:
String file2string(File f, Charset cs) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
InputStream in = new BufferedInputStream(new FileInputStream(f));
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
return out.toString(cs.name());
}
If you don't know the source encoding, rely on the XML parser to detect it and control the output:
String transform2String(File f, Charset cs) throws IOException,
TransformerFactoryConfigurationError, TransformerException {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.ENCODING, cs.name());
ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
t.transform(new StreamSource(new BufferedInputStream(
new FileInputStream(f))), new StreamResult(out));
return out.toString(cs.name());
}
精彩评论