Issue
I'm currently working on a data processing project in Java and need to handle both XML and CSV files. I'm relatively new to file manipulation in Java and looking for guidance on efficiently reading and writing data in these formats. Here are my specific queries.
Only Java standard libs are acceptable. Because the version dependence of external libs are too complex
Solution
write csv file
public static void main(String[] args) {
String csvFilePath = "test.csv";
try (FileWriter csvWriter = new FileWriter(csvFilePath)) {
//FileWriter csvWriter = new FileWriter(csvFilePath, true) can write in a addition mode
// Write the header
csvWriter.append("Name, Age, City\n");
// Write some data rows
csvWriter.append("John Doe, 25, New York\n");
csvWriter.append("Jane Smith, 30, San Francisco\n");
} catch (IOException e) {
e.printStackTrace();
}
}
each data is a liststring and the data variable should be list of list string
read csv
public class readCsv {
public static void main(String[] args) {
String csvFilePath = "test.csv";
try {
// Read all lines from the CSV file into a List
List<String> lines = Files.readAllLines(Paths.get(csvFilePath));
// Process each line
for (String line : lines) {
// Split the line into fields based on the CSV format (comma-separated)
String[] fields = line.split(",");
// Process the fields as needed
for (String field : fields) {
System.out.print(field + " ");
}
System.out.println(); // Move to the next line for the next record
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
csvfilePath is the file path which you want to read
create a new XML
try {
// Create a DocumentBuilder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// Create a new Document
Document document = builder.newDocument();
// Create root element
Element rootElement = document.createElement("people");
document.appendChild(rootElement);
// Create person elements
Element person1 = document.createElement("person");
Element name1 = document.createElement("name");
Element age1 = document.createElement("age");
name1.appendChild(document.createTextNode("John Doe"));
age1.appendChild(document.createTextNode("30"));
person1.appendChild(name1);
person1.appendChild(age1);
Element person2 = document.createElement("person");
Element name2 = document.createElement("name");
Element age2 = document.createElement("age");
name2.appendChild(document.createTextNode("Alice Smith"));
age2.appendChild(document.createTextNode("25"));
person2.appendChild(name2);
person2.appendChild(age2);
rootElement.appendChild(person1);
rootElement.appendChild(person2);
// Write the XML content to a file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("path/to/your/output/file.xml"));
transformer.transform(source, result);
System.out.println("XML data written to file");
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it's helpful
Add a way to read plain text:
public static String read(String filePath) {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(content.toString());
return content.toString();
}
read xml file
public class ReadXml {
public static void main(String[] args) {
try {
// Specify the path to your XML file
//attention the directory is based on your root directory
File inputFile = new File("yourfile.xml");
// Create a DocumentBuilderFactory
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
// Create a DocumentBuilder
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
// Parse the XML file to create a Document object
Document doc = dBuilder.parse(inputFile);
// Optional: normalize the document to remove unnecessary whitespace
doc.getDocumentElement().normalize();
// Get the root element
System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
//Get a NodeList of elements with a specific tag name
NodeList nodeList = doc.getElementsByTagName("element");
// Iterate through the NodeList
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
// Check if the node is an element node
if (node.getNodeType() == Node.ELEMENT_NODE) {
// Get element attributes or text content
System.out.println("Element: " + node.getNodeName());
// Example: Get text content of an element
System.out.println("Value: " + node.getTextContent());
// Example: Get attribute value
// String attributeValue = ((Element) node).getAttribute("attributeName");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
the former write xml is to create a Xml file. Now there is a method to add data to an existing method.
public class AddXml {//add data to an existing content
//xml structure L1:<company> L2:<employee> L3:<id><name><position><salary>
public static void main(String[] args) {
try {
// Specify the path to your XML file
File inputFile = new File("src/company.xml");
// Create a DocumentBuilderFactory
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
// Create a DocumentBuilder
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
// Parse the XML file to create a Document object
Document doc = dBuilder.parse(inputFile);
// Optional: normalize the document to remove unnecessary whitespace
doc.getDocumentElement().normalize();
// Get the root element
Element rootElement = doc.getDocumentElement();//root:company
// Create a new element to add to the XML file: first create then give value
Element newEmployee = doc.createElement("employee");
Element newID = doc.createElement("id");
newID.setTextContent("1234");
Element newName = doc.createElement("name");
newName.setTextContent("tester");
Element newPos = doc.createElement("position");
newPos.setTextContent("Internship");
Element newSalary = doc.createElement("salary");
newSalary.setTextContent("10000");
newEmployee.appendChild(newID);
newEmployee.appendChild(newName);
newEmployee.appendChild(newPos);
newEmployee.appendChild(newSalary);
// Append the new element to the root element
rootElement.appendChild(newEmployee);
// Write the modified document back to the XML file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(inputFile);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
write plain text:
String mdFilePath = "path/to/your/file.md";
try {
// Content to be written to the Markdown file
String content = "# Heading 1\n\nThis is a paragraph.\n\n* Bullet 1\n* Bullet 2\n";
// Write content to the Markdown file
Path path = Paths.get(mdFilePath);
Files.write(path, content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
System.out.println("Markdown file created successfully: " + mdFilePath);
} catch (IOException e) {
e.printStackTrace();
}
Answered By - Pass1912
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.