厦门市建设局网站文件,北京工商注册网官网,企业网站 jquery,wordpress 添加表格前言#xff1a;Hadoop采用java语言开发#xff0c;提供了Java Api与HDFS进行交互
先要把hadoop的jar包导入到idea中去
为了能编写一个与hdfs交互的java应用程序#xff0c;一般需要向java工程中添加以下jar包
1#xff09;/usr/local/hadoop/share/hadoop/common目录下…前言Hadoop采用java语言开发提供了Java Api与HDFS进行交互
先要把hadoop的jar包导入到idea中去
为了能编写一个与hdfs交互的java应用程序一般需要向java工程中添加以下jar包
1/usr/local/hadoop/share/hadoop/common目录下的所有jar包
2/usr/local/hadoop/share/hadoop/common/lib下的所有jar包
3/usr/local/hadoop/share/hadoop/hdfs目录下的所有jar包
4/usr/local/hadoop/share/hadoop/hdfs/lib中的所有jar包
1、先从本地上传个文件到HDFS中去
命令
hdfs dfs -cp -f file:///usr/local/hadoop/a b 2、在idea中创建项目
HDFSAPI.java import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;import java.io.File;
import java.io.IOException;//从HDFS中下载指定文件如果本地文件与要下在文件名相同则自动对下载的文件重命名
public class HDFSAPI {public static void copyToLocal(Configuration conf , String remoteFilePath, String localFilePath)throws IOException{FileSystem fs FileSystem.get(conf);Path remotePath new Path(remoteFilePath);File f new File(localFilePath);//如果文件名存在自动重命名在文件后面加上_0,_1if (f.exists()){System.out.println(localFilePath已存在!);Integer i 0;while (true){fnew File(localFilePath_i.toString());if (!f.exists()){localFilePathlocalFilePath_i.toString();}i;System.out.println(将文件重命名localFilePath);break;}}//下载到本地Path localPathnew Path(localFilePath);fs.copyToLocalFile(remotePath,localPath);fs.close();}}
Main.java
import org.apache.hadoop.conf.Configuration;public class Main{public static void main(String[] args) {Configuration configuration new Configuration();configuration.set(fs.default.name,hdfs://localhost:9000);//本地路径String localFilePath/home/hadoop/text.txt;//hdfs路径String remoteFilePath/user/hadoop/b;try {HDFSAPI.copyToLocal(configuration,remoteFilePath,localFilePath);System.out.println(下载完成!);}catch (Exception e){e.printStackTrace();}}
}3、将该项目打包成jar包
File-Project Structure 打包的文件在idea当前项目的out文件夹里面 4、将打包好的jar包移动到hadoop的安装目录下
我这里在hadoop的安装目录下新建了个myapp的文件夹 5、运行
./bin/hadoop jar ./myapp/HDFS_API.jar