将XML文件保存到HDFS

将XML文件保存到HDFS,xml,scala,apache-spark,Xml,Scala,Apache Spark,我有一个XML字符串,需要保存到HDFS位置 <transportation-carrier> <SCAC>LKSKS</SCAC> <name>JACKSONVILLE Name</name> <billing-road-number>139</billing-road-number> <effective-date>2017-03-08</effective-date> <exp

我有一个XML字符串,需要保存到HDFS位置

<transportation-carrier>
<SCAC>LKSKS</SCAC>
<name>JACKSONVILLE Name</name>
<billing-road-number>139</billing-road-number>
<effective-date>2017-03-08</effective-date>
<expiration-date>2017-03-07</expiration-date>
</transportation-carrier>
我收到了这个错误消息-

线程“main”java.io.FileNotFoundException:\data\temp\example.xml中出现异常(系统找不到指定的路径)


如果能帮助我将文件保存到HDFS路径,我将不胜感激。

我最终将字符串XML转换为XML文件,然后使用Scala的DataRicks包将其转换为数据帧。

假设Spark和Hadoop env,另一种方法是使用java.io和XML.write方法,而不是save

它不需要中间文件:

import org.apache.hadoop.fs.{ FileSystem, Path, FSDataOutputStream }
import java.io.BufferedWriter
import java.io.OutputStreamWriter

val xmlRoot : Elem = <myElem>test</myElem>
val path: Path = new Path("hdfs:///myfile.xml")
if (fs.exists(path)) {
   fs.delete(path, true)
}
val dataOutputStream: FSDataOutputStream = fs.create(path)
val bw: BufferedWriter = new BufferedWriter(new OutputStreamWriter(dataOutputStream, "UTF-8"))
XML.write(bw, xmlRoot, "utf-8", xmlDecl = true, doctype = null)
bw.close()
import org.apache.hadoop.fs.{文件系统,路径,FSDataOutputStream}
导入java.io.BufferedWriter
导入java.io.OutputStreamWriter
val xmlRoot:Elem=test
val路径:路径=新路径(“hdfs:///myfile.xml")
如果(fs.exists(path)){
fs.delete(路径,true)
}
val dataOutputStream:FSDataOutputStream=fs.create(路径)
val bw:BufferedWriter=新的BufferedWriter(新的OutputStreamWriter(dataOutputStream,“UTF-8”))
write(bw,xmlRoot,“utf-8”,xmlDecl=true,doctype=null)
bw.close()

适用于Cloudera+齐柏林飞艇环境。

我不确定您是否在这里使用SPARK。如果您试图从独立的Scala应用程序编写该文件,可以尝试检查我是否正在使用Spark连接群集。我在代码中没有看到任何对Spark上下文和RDD的引用。如果您正在使用这些东西,那么您可以使用rdd.saveasxxxapi
import org.apache.hadoop.fs.{ FileSystem, Path, FSDataOutputStream }
import java.io.BufferedWriter
import java.io.OutputStreamWriter

val xmlRoot : Elem = <myElem>test</myElem>
val path: Path = new Path("hdfs:///myfile.xml")
if (fs.exists(path)) {
   fs.delete(path, true)
}
val dataOutputStream: FSDataOutputStream = fs.create(path)
val bw: BufferedWriter = new BufferedWriter(new OutputStreamWriter(dataOutputStream, "UTF-8"))
XML.write(bw, xmlRoot, "utf-8", xmlDecl = true, doctype = null)
bw.close()