赞
踩
将一个本地文件(无具体要求)上传至HDFS中的/hdfs-test路径下(如无此路径,新建一个)。
新建路径:
首先在路径/usr/test/ 下新建test.txt,指令为:/usr/test/test.txt,然后进行上传操作。
- package org.apache.hadoop.examples;
- import java.io.FileInputStream;
- public class module_info {
-
- public static void main(String[] args) throws Exception {
- Configuration conf=new Configuration();
- URI uri=new URI("hdfs://192.168.46.xxx:9000");
- FileSystem fs=FileSystem.get(uri,conf,"hadoop");
- Path src=new Path("/usr/test/test.txt");
- Path dst=new Path("/hdfs-test/test.txt");
- fs.copyFromLocalFile(src, dst);
- fs.close();
- System.out.println("Upload Successfully!");
- // TODO Auto-generated method stub
-
- }
-
- }

2.HDFS-JAVA接口:创建文件
在HDFS中的/hdfs-test路径下新建一个data.txt文件。
- package org.apache.hadoop.examples1;
- import java.io.FileInputStream;
- public class CreateText {
- public static void main(String[] args) throws Exception{
- // TODO Auto-generated method stub
- Configuration conf = new Configuration();
- URI uri = new URI("hdfs://192.168.46.xxx:9000");
- FileSystem fs = FileSystem.get(uri, conf, "hadoop");
- Path path = new Path("/hdfs-test/data.txt");
- FSDataOutputStream newFile = fs.create(path, true);
- newFile.writeBytes("hello");
- newFile.close();
- fs.close();
- }
- }
查询发现/hdfs-test路径下新建了一个data.txt文件
输入指令查看文件内容
3.HDFS-JAVA接口:下载文件
将HDFS中的/hdfs-test/data.txt文件下载到本地任一路径下。
- package org.apache.hadoop.examples;
- import java.net.URI;
- public class DownloadText {
- public static void main(String[] args) throws Exception {
- Configuration conf=new Configuration();
- URI uri=new URI("hdfs://192.168.46.xxx:9000");
- FileSystem fs=FileSystem.get(uri,conf,"hadoop");
- Path src=new Path("/hdfs-test/data.txt");
- Path dst=new Path("/usr/test/data.txt");
- fs.copyToLocalFile(false,src,dst,true);
- fs.close();
- System.out.println("Download Successfully!");
- // TODO Auto-generated method stub
- }
- }
根据路径/usr/test/data.txt查看内容,发现下载的文件data.txt
4.HDFS-JAVA接口:删除文件
将HDFS中/hdfs-test路径下的data.txt删除。
- package org.apache.hadoop.examples;
- import java.net.URI;
-
- public class DeleteTxt {
-
- public static void main(String[] args) throws Exception {
- Configuration conf=new Configuration();
- URI uri=new URI("hdfs://192.168.46.xxx:9000");
- FileSystem fs=FileSystem.get(uri,conf,"hadoop");
- Path path=new Path("/hdfs-test/data.txt");
- fs.delete(path);
- fs.close();
- System.out.println("Delete File Successdully!");
-
- // TODO Auto-generated method stub
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。