如何使用Java代码将文件上载和下载到hdfs

时间:2014-12-24 08:49:44

标签: java hadoop

我是hadoop的新手,并试图通过上传和下载文件到hdfs。 Java代码。应该表现为

数据上传:

 hadoop fs -put or -copyFromLocal filename directoryName

和数据下载

  hadoop fs -get or -copyToLocal filename directoryName
来自hdfs。我需要这个,因为数据集包含图像,音频,视频等文件。上面的命令适用于所有类型的数据,如果我尝试使用Java i / o阅读器代码,它适用于文本文件,但不适用于图像,视频。 docx等..

请在这里提供帮助。

在此编辑:

public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        Configuration conf=new Configuration();
        FileSystem fs = FileSystem.get(conf);

        Path path=new Path("data");
        Path file=new Path(path,"screenshots.png");

        BufferedImage image = ImageIO.read(new File("/home/hduser/Desktop/screenshots.png"));
        if (!fs.exists(path))
          throw new IOException("Output not found!");

        ImageIO.write(image, "png", fs.open(path));


    }

正如我所知,我在这里编辑了用于将图像文件上传到hdfs的代码。这里ImageIO.write不接受争论fs.open(path),因为要求文件,但我必须在这里给路径读取和写入hdfs我们只需要提供路径。实际上我需要一种使用所有类型数据的代码从hdfs上传和下载文件的方法,所以我不应该为所有类型的文件编写代码并使用插件。

2 个答案:

答案 0 :(得分:2)

ImageIO.write可以使用OutputStream和File。但是,fs.open返回一个InputStream,因为它只用于读取文件。

您需要致电:

ImageIO.write(image, "png", fs.create(file));

create方法将返回ImageIO可以写入的OutputStream

http://hadoop.apache.org/docs/r2.2.0/api/org/apache/hadoop/fs/FileSystem.html

答案 1 :(得分:0)

  1. 如果path已经存在,那么您将用图像覆盖该文件。我认为您要将图像保存到HDFS中的某个现有文件夹中。在这种情况下,您需要将图像写入new Path(path, "SomeImageName.png");
  2. 您不需要使用ImageIO将图像从本地文件系统复制到HDFS。尝试使用copyFromLocalFile的{​​{1}}方法:

    fs.copyFromLocalFile(新路径(" /home/hduser/Desktop/screenshots.png"),路径);