1.新建一个Java项目
将lib包导入
将core-site.xml与hdfs-site.xml导入新建的conf文件夹
core-site.xml与hdfs-site.xml就是伪分布式虚拟机中的core-site.xml与hdfs-site.xml
新建测试类
编写代码
package com.hpe.test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.omg.Messaging.SyncScopeHelper;
public class TestHdfs {
//引入配置文件
Configuration conf=null;
//创建文件流----引用的是hadoop内部封装的方法
FileSystem fs=null;
@Before
public void conn() throws Exception{
conf=new Configuration(true);//设置是否读取配置信息
fs=FileSystem.get(conf);
}
@After
public void close() throws Exception{
fs.close();
}
//创建、删除、重命名、判断是否存在
//创建文件
@Test
public void mkdir() throws Exception{
Path f=new Path("/aaa");
//判断是否存在
if(fs.exists(f)){
//删除
fs.delete(f);
}
//创建
fs.mkdirs(f);
}
//自己补充完成
public void exist(){
}
//重命名
@Test
public void rn() throws Exception{
Path p1 = new Path("/user/root/passwd");
Path p2 = new Path("/user/root/haha.txt");
boolean rename = fs.rename(p1, p2);
System.out.println(rename);
}
//上传文件
@Test
public void uploadFile() throws Exception{
//输出位置
Path inputFile=new Path("/tmpDir/haha.txt");
//相当于文件内容的输出
FSDataOutputStream output = fs.create(inputFile);
//输入位置,相当于文件内容的输入
InputStream input=new BufferedInputStream(new FileInputStream(new File("d:\\124.txt")));
IOUtils.copyBytes(input, output, conf, true);
}
//下载文件
@Test
public void downloadFile() throws Exception{
//上传文件到HDFS
Path src = new Path("/tmpDir/haha.txt");
//输入源:将我集群中的文件作为输入
FSDataInputStream input=fs.open(src);
//输出位置
FileOutputStream output=new FileOutputStream("F://aa.txt");
IOUtils.copyBytes(input, output, conf, true);
}
//上传下载
}
完成