簡體   English   中英

如何使用Java代碼將文件上傳和下載到hdfs

[英]How to upload and download file to hdfs using Java code

我是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上傳和下載文件的方法,因此我不應該編寫代碼並針對所有類型的文件使用插件。

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. 如果path已經存在,那么您將用映像覆蓋該文件。 我認為您想將圖像保存到HDFS某些現有文件夾中。 在這種情況下,您需要將圖像寫入new Path(path, "SomeImageName.png");
  2. 您無需使用ImageIO將映像從本地文件系統復制到HDFS 嘗試使用FileSystem copyFromLocalFile方法:

    fs.copyFromLocalFile(new Path(“ / home / hduser / Desktop / screenshots.png”),路徑);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM