java创建XML文件到本地并写入数据

1.创建XML,添加内容,然后写入到本地。

采用DOM(JAXP Crimson解析器)处理,Java提供了四种处理方法,这里选取其一

//整体思路,
//创建文档构建器工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//创建一个文档构建器,此处需要try,catch处理一下
DocumentBuilder db = factory.newDocumentBuilder();
// 创建xmldoc文档对象,用来创建节点。
Document xmldoc = db.newDocument();
// 创建books根节点
books = xmldoc.createElement("books");

// 将books根节点添加到xmldoc上
xmldoc.appendChild(books);

//然后就是在根节点下添加新的节点,先创建新节点,给新节点添加文本属性,或者创建文本节点,将文本节点添加到新节点上。
theBook = xmldoc.createElement("book");
// --- 另外还想加一个属性id,值为B01 ----
theBook.setAttribute("id", "B01");
theElem = xmldoc.createElement("name");
//给新节点添加文本属性
theElem.setTextContent("哈里波特");
//创建文本节点,将文本节点添加到新节点上。
//theElem.appendChild(xmldoc.createTextNode("哈里波特2"));
//theBook 下添加theElem节点
theBook.appendChild(theElem);
//books根节点下添加theBook节点
books.appendChild(theBook);

可以将每次创建新节点,添加到父节点上的步骤封装起来,便于代码复用

	// 添加子节点到该节点上(父节点对象,子节点名称,子节点文本)
	public void addChildElement(Element element, String child_ele_name, String text) {
		Document doc = element.getOwnerDocument();
		Element sub_element = createLeafElement(doc, child_ele_name, text);
		element.appendChild(sub_element);
	}

	// 创建叶节点(无子节点的节点)(文档对象,节点名,节点文本)
	public Element createLeafElement(Document doc, String eleName, String text) {
		// 创建节点需要doc对象
		Element ele = doc.createElement(eleName);
		if (text != null) {
			// 创建文本节点,并添加到叶子节点上。
			ele.appendChild(doc.createTextNode(text));
		}
		return ele;
	}

下面看一个具体实例,运行main方法即可。

xml格式
<?xml version="1.0" encoding="GB2312" standalone="no"?>
<books>
	<book id="B01">
		<name>神雕侠侣</name>
		<price>10</price>
		<memo>徒弟和师傅外加一只雕的故事。</memo>
	</book>
</books>
package com.leo.xml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class NewXMl {
	public static void main(String[] args) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		try {
			db = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		// 声明3个变量,可以复用。
		Element books = null, Book = null, Elem = null;
		// 创建xmldoc对象,用来创建节点。
		Document xmldoc = db.newDocument();
		
		// 创建books节点
		books = xmldoc.createElement("books");
		// 将books节点添加到xmldoc上
		xmldoc.appendChild(books);

		Book = xmldoc.createElement("book");
		// --- 另外还想加一个属性id,值为B01 ----
		Book.setAttribute("id", "B01");
		Elem = xmldoc.createElement("name");
		Elem.setTextContent("笑傲江湖");
		//Elem.appendChild(xmldoc.createTextNode("天龙八部"));
		Book.appendChild(Elem);
		Elem = xmldoc.createElement("price");
		Elem.setTextContent("20");
		Book.appendChild(Elem);
		Elem = xmldoc.createElement("memo");
		Elem.setTextContent("令狐冲与东方不败的爱恨情仇。");
		Book.appendChild(Elem);
		books.appendChild(Book);
		
		
		// ** 将document中的内容写入文件中 *//*
		// 创建TransformerFactory对象
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer;
		try {
			// 创建transformer 对象
			transformer = tFactory.newTransformer();
			// ** 设置xml编码 格式**
			transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
			DOMSource source = new DOMSource(xmldoc);
			//设置本地保存路径
			StreamResult result = new StreamResult(new File("D:/123.xml"));
			transformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		
	}

	
}

最后,可以了解一下,Java读取XML数据,采用Dom方式

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 在Java应用程序中读取HBase表中的数据并将其存储到本地文件中,你需要以下步骤: 1. 在你的Java应用程序中添加HBase的依赖,你可以在pom.xml中添加如下依赖: ``` <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>1.4.12</version> </dependency> ``` 2. 创建HBase Configuration对象并设置HBase连接的相关参数,例如zookeeper地址和端口。 ``` Configuration config = HBaseConfiguration.create(); config.set("hbase.zookeeper.quorum", "zookeeper1,zookeeper2,zookeeper3"); config.set("hbase.zookeeper.property.clientPort", "2181"); ``` 3. 创建HBase连接,使用HBase Configuration对象作为参数。 ``` Connection connection = ConnectionFactory.createConnection(config); ``` 4. 获取HBase表的实例,使用HBase连接和表名作为参数。 ``` Table table = connection.getTable(TableName.valueOf(tableName)); ``` 5. 使用HBase Scan对象指定要读取的列,然后使用HBase Table对象的getScanner方法执行Scan操作,获取结果集。 ``` Scan scan = new Scan(); scan.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(column)); ResultScanner scanner = table.getScanner(scan); ``` 6. 遍历结果集,并将数据写入本地文件。你可以使用java.io.FileOutputStream和java.io.OutputStreamWriter将数据写入文件。 ``` FileOutputStream fos = new FileOutputStream(new File(filePath)); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); for (Result result : scanner) { String rowKey = Bytes.toString(result.getRow()); String value = Bytes.toString(result.getValue(Bytes.toBytes(columnFamily), ### 回答2: 以下是一个示例代码,用于使用Java应用程序读取HBase中的表数据并将其存储到本地文件中: ```java import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; public class HBaseToTextFile { public static void main(String[] args) throws IOException { // 创建HBase配置对象 Configuration conf = HBaseConfiguration.create(); // 设置HBase配置参数,例如HBase的zk地址 conf.set("hbase.zookeeper.quorum", "localhost"); conf.set("hbase.zookeeper.property.clientPort", "2181"); // 创建HBase连接对象 try (Connection connection = ConnectionFactory.createConnection(conf)) { // 获取表对象 TableName tableName = TableName.valueOf("your_table_name"); Table table = connection.getTable(tableName); // 创建扫描对象 Scan scan = new Scan(); // 执行扫描操作,获取结果集 ResultScanner scanner = table.getScanner(scan); // 创建文件写入对象 try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")))) { // 遍历结果集 for (Result result : scanner) { // 获取单元格列表 List<Cell> cells = result.listCells(); // 遍历单元格列表,将数据写入文件中 for (Cell cell : cells) { byte[] rowArray = CellUtil.cloneRow(cell); byte[] familyArray = CellUtil.cloneFamily(cell); byte[] qualifierArray = CellUtil.cloneQualifier(cell); byte[] valueArray = CellUtil.cloneValue(cell); // 将字节数组转换为字符串 String row = Bytes.toString(rowArray); String family = Bytes.toString(familyArray); String qualifier = Bytes.toString(qualifierArray); String value = Bytes.toString(valueArray); // 写入文件 writer.println(row + "," + family + "," + qualifier + "," + value); } } // 输出完成信息 System.out.println("数据已经写入到本地文件。"); } } } } ``` 请注意,上述代码需要使用HBase的相关jar包,以及Hadoop的相关配置。你需要根据自己的环境进行相应的配置和引入相应的依赖。 ### 回答3: 可以使用Java应用程序通过HBase的Java API来读取表的数据并存储,然后使用IO流将数据写入本地文件。 以下是一个简单的示例代码: ```java import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.*; import java.io.*; public class HBaseDataExporter { public static void main(String[] args) throws IOException { // 设置HBase配置 Configuration config = HBaseConfiguration.create(); config.set("hbase.zookeeper.quorum", "localhost"); // HBase的ZooKeeper地址 config.set("hbase.zookeeper.property.clientPort", "2181"); // ZooKeeper端口 // 创建HBase连接 Connection connection = ConnectionFactory.createConnection(config); // 获取表 TableName tableName = TableName.valueOf("yourTableName"); // 表名 Table table = connection.getTable(tableName); // 创建本地文件输出流 FileWriter fileWriter = new FileWriter("data.txt"); // 扫描表中的数据写入文件 ResultScanner scanner = table.getScanner(new Scan()); for (Result result : scanner) { // 获取行键 String rowKey = Bytes.toString(result.getRow()); // 获取所有列族和列的数据 for (Cell cell : result.listCells()) { // 获取列族 String family = Bytes.toString(CellUtil.cloneFamily(cell)); // 获取列名 String qualifier = Bytes.toString(CellUtil.cloneQualifier(cell)); // 获取值 String value = Bytes.toString(CellUtil.cloneValue(cell)); // 将数据写入文件 fileWriter.write("RowKey: " + rowKey + ", Family: " + family + ", Qualifier: " + qualifier + ", Value: " + value + "\n"); } } // 关闭资源 scanner.close(); table.close(); connection.close(); fileWriter.close(); } } ``` 这个示例程序通过HBase的Java API连接到HBase,然后扫描指定表中的数据。每次获取到一行数据后,遍历所有的列族和列,并将数据写入本地文件"data.txt"中。 请注意,你需要将代码中的"yourTableName"替换为实际的表名,并且根据实际情况修改HBase的配置信息。 希望这个示例能帮助到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

跳舞 D 猴子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值