HDFS基本实现
获取Configration并设置
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://localhost:9000"); //设置默认FS位置,设置为hdfs的地址
configuration.set("fs.hdfs.impl","org.apache.hadoop.hdfs.DistributedFileSystem"); //HDFS文件操作类设置,设置为DFS
更多端口配置信息
https://blog.csdn.net/cuitaixiong/article/details/51591410
获取FileSystem
FileSystem fs = FileSystem.get(configuration);
获取读写流
FSDataInputStream is = fs.open(new Path(fileName));
FSDataOutputStream os = fs.create(new Path(fileName));
注意点:
1.FSDataInputStream 和 FSDataOutputStream会自动判断FS类型并自适应,所以无论是DFS还是普通的FS都可以使用这两个输入输出流。
2.输出流的create会在不存在文件的时候自动创建,若已有则进行覆盖,具体可见源码。
完整JAVA实现
最后一定要关闭读写流和FS!!!
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 java.io.BufferedReader;
import java.io.InputStreamReader;
public class sad {
private static void read(FileSystem fs,String fileName){
try {
FSDataInputStream is = fs.open(new Path(fileName));
BufferedReader br =new BufferedReader(new InputStreamReader(is));
String str = br.readLine();
System.out.println(str);
is.close();
fs.close();
}catch (Exception e){
e.printStackTrace();
}
}
private static void write(FileSystem fs,String fileName){
try {
byte[] data = "Hello spark!".getBytes();
FSDataOutputStream os = fs.create(new Path(fileName));
os.write(data,0,data.length);
System.out.println("Create done!");
os.close();
fs.close();
}catch (Exception e){
e.printStackTrace();
}
}
private static void isExists(FileSystem fs,String fileName){
try {
if(fs.exists(new Path(fileName))){
System.out.println("is exists");
}else{
System.out.println("not exists");
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
try{
String fileName = "test";
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://localhost:9000");
configuration.set("fs.hdfs.impl","org.apache.hadoop.hdfs.DistributedFileSystem");
FileSystem fs = FileSystem.get(configuration);
isExists(fs,fileName);
write(fs,fileName);
read(fs,fileName);
}catch (Exception e){
e.printStackTrace();
}
}
}
最后一定要关闭读写流和FS!!!
关于报错
错误 | 解决方法 |
---|---|
java.lang.NoClassDefFoundError | 检查是否导入包hadoop-common-2.7.1.jar和haoop-nfs-2.7.1.jar;/usr/local/hadoop/share/hadoop/common/lib”目录下的所有JAR包;“/usr/local/hadoop/share/hadoop/hdfs”目录下的haoop-hdfs-2.7.1.jar和haoop-hdfs-nfs-2.7.1.jar;“/usr/local/hadoop/share/hadoop/hdfs/lib”目录下的所有JAR包。 |
学习计划
-2019年4月中旬基本掌握Hadoop的基础操作
-2019年5月中旬基本掌握spark的基础操作
-2019年6月中旬能够完成一系列基础实战