Saturday, May 20, 2023

How to Read XML File as String in Java? 3 Examples

Using java.io.BufferedReader:



import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class XMLReaderExample {
    public static void main(String[] args) {
        String filePath = "path/to/your/xml/file.xml";
        StringBuilder xmlString = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                xmlString.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String xmlContent = xmlString.toString();
        System.out.println(xmlContent);
    }
}


Using java.nio.file.Files:



import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class XMLReaderExample {
    public static void main(String[] args) {
        String filePath = "path/to/your/xml/file.xml";
        String xmlContent = "";
        try {
            Path path = Paths.get(filePath);
            byte[] bytes = Files.readAllBytes(path);
            xmlContent = new String(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(xmlContent);
    }
}


Using Apache Commons IO:


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class XMLReaderExample {
    public static void main(String[] args) {
        String filePath = "path/to/your/xml/file.xml";
        String xmlContent = "";
        try {
            Path path = Paths.get(filePath);
            byte[] bytes = Files.readAllBytes(path);
            xmlContent = new String(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(xmlContent);
    }
}

These examples demonstrate different approaches to read an XML file as a string in Java using different libraries and APIs. Choose the one that suits your needs and make sure to replace "path/to/your/xml/file.xml" with the actual file path of your XML file.

No comments:

Post a Comment