Suponga la codificación UTF8 en el archivo; si no es así, simplemente omita el argumento «UTF8» y usará el juego de caracteres predeterminado para el sistema operativo subyacente en cada caso.
Manera rápida en JSE 6 – ¡Simple y sin biblioteca de terceros!
import java.io.File;
public class FooTest {
@Test public void readXMLToString() throws Exception {
java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
//Z means: "The end of the input but for the final terminator, if any"
String xml = new java.util.Scanner(new File(url.toURI()),"UTF8").useDelimiter("\Z").next();
}
}
Manera rápida en JSE 7
public class FooTest {
@Test public void readXMLToString() throws Exception {
java.net.URL url = MyClass.class.getResource("test/resources/abc.xml");
java.nio.file.Path resPath = java.nio.file.Paths.get(url.toURI());
String xml = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");
}
Manera rápida desde Java 9
new String(getClass().getClassLoader().getResourceAsStream(resourceName).readAllBytes());
Sin embargo, ninguno de los dos está destinado a archivos enormes.