RHDFS输出中的字符串字符

时间:2015-01-09 01:09:17

标签: rhadoop

rhdfs中的hdfs.write()命令创建一个带有前导非Unicode字符的文件。文档没有描述正在编写的文件类型。

重新创建的步骤。 1.打开R并初始化rhdfs

> ofile = hdfs.file("brian.txt", "w")
> hdfs.write("hi",ofile)
> hdfs.close(ofile)

创建一个名为" brian.txt"的文件。我可以期待包含一个字符串," hi"。但这开头就显露出了额外的性格。

> hdfs dfs -cat brian.txt
X
    hi

我不知道创建了什么文件类型,rhdfs没有显示任何文件类型选项。这使输出很难使用。

2 个答案:

答案 0 :(得分:3)

如果查看source code中的hdfs.write函数,可以看到它可以占用原始字节而不是让R为它序列化。所以基本上你可以为角色

做这件事
ofile = hdfs.file("brian.txt", "w")
hdfs.write(charToRaw("hi", ofile))
hdfs.close(ofile)

答案 1 :(得分:1)

默认情况下,Hadoop会在您直接创建/写入时序列化对象,因此您会在文件中看到额外的字符。但是,当您使用copyFromLocal将文本文件从local复制到hadoop时,情况并非如此。

序列化是将结构化对象转换为字节流的过程。它基本上有两个目的: 1)用于通过网络传输(进程间通信)。 2)用于写入持久存储。

您可以使用以下R代码反序列化hadoop对象:

hfile = hdfs.file("brian.txt", "r") # read from hdfs
file <- hdfs.read(hfile) 
file <- unserialize(file) # deserialize to remove special characters
hdfs.close(hfile)

如果您计划从R创建文件,但是不会通过R读取,那么避免特殊字符的解决方法是将内容保存到本地文件并将文件移动到hdfs。以下是R代码:

# Set environment path and load library
Sys.setenv("HADOOP_CMD"="/usr/local/hadoop/bin/hadoop")
library(rhdfs)
hdfs.init()  # Initialize

text <- "Hi, This is a sample text."
SaveToLocalPath <- "/home/manohar/Temp/outfile.txt"
writeLines(text, SaveToLocalPath) # write content to local file
hdfs.put(SaveToLocalPath, "/tmp") # Copy file to hdfs
file.remove(SaveToLocalPath) # Delete from local
相关问题