java操作HDFS增删改查

第一步:下载java所依赖的java包,这里使用maven下载,使用maven下载hadoop依赖包可能出现依赖冲突,即有2个相同maven依赖包,推荐使用如下方法下载

在pom.xml里面添加如下

<dependency>  
    <groupId>org.apache.hadoop</groupId>  
    <artifactId>hadoop-common</artifactId>  
    <version>2.6.0</version>  
    <exclusions>  
        <exclusion>  
            <artifactId>servlet-api</artifactId>  
            <groupId>javax.servlet</groupId>  
        </exclusion>  
        <exclusion>  
            <artifactId>jasper-compiler</artifactId>  
            <groupId>tomcat</groupId>  
        </exclusion>  
        <exclusion>  
            <artifactId>jasper-runtime</artifactId>  
            <groupId>tomcat</groupId>  
        </exclusion>  
        <exclusion>  
            <artifactId>jsp-api</artifactId>  
            <groupId>javax.servlet.jsp</groupId>  
        </exclusion>  
    </exclusions>  
</dependency>  
  
<dependency>  
    <groupId>org.apache.hadoop</groupId>  
    <artifactId>hadoop-hdfs</artifactId>  
    <version>2.6.0</version>  
    <exclusions>  
        <exclusion>  
            <artifactId>servlet-api</artifactId>  
            <groupId>javax.servlet</groupId>  
        </exclusion>  
    </exclusions>  

</dependency>

如果没有maven没有依赖,可以直接在pom.xml添加如下

<dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-hdfs</artifactId>
      <version>2.6.0</version>
  </dependency>


  <dependency>  
      <groupId>org.apache.hadoop</groupId>  
      <artifactId>hadoop-client</artifactId>  
      <version>2.6.0</version>  
  </dependency> 


  <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-common</artifactId>
      <version>2.6.0</version>

  </dependency>

第2步java从HDFS进行应用开发

public class HdfsDemo {

	/**
	 * @param krb5File
	 *            对应conf的krb5.conf配置文件
	 * @param user
	 *            验证用户名
	 * @param keytabPath
	 *            对应asmp.keytab配置文件
	 * @return Configuratio配置对象
	 * @throws IOException
	 */
	public static Configuration getConfig(String krb5File, String user,
			String keytabPath) throws IOException {

		Configuration conf = new Configuration();

		conf.set("fs.hdfs.impl",
				org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());

		System.setProperty("java.security.krb5.conf", krb5File);
		// if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
		// System.setProperty("java.security.krb5.conf", krb5File);
		// } else {
		// // linux系统也可不设,其会自动去寻找 /etc/krb5.conf
		// System.setProperty("java.security.krb5.conf", krb5File);
		// }

		conf.set("hadoop.security.authentication", "kerberos");
		/* conf.set("fs.defaultFS", "hdfs://svlhdpt01-pip.csvw.com:8020"); */
		UserGroupInformation.setConfiguration(conf);
		UserGroupInformation.loginUserFromKeytab(user, keytabPath);
		return conf;
	}

	/**
	 * 获取Hdfs 指定目录下所有文件
	 * 
	 * @param URI
	 *            hdfs远端连接url
	 * @param remotePath
	 *            hdfs远端目录路径
	 * @param conf
	 * @throws Exception
	 */
	public static void getHdfsFileList(String URI, String remotePath,
			Configuration conf) throws Exception {

		FileSystem fs = FileSystem.get(new URI(URI), conf);
		RemoteIterator<LocatedFileStatus> iter = fs.listFiles(new Path(
				remotePath), true);
		while (iter.hasNext()) {
			LocatedFileStatus status = iter.next();
			System.out.println(status.getPath().toUri().getPath());
		}
		fs.close();
	}

	/**
	 * 下载 hdfs上的文件
	 * 
	 * @param conf
	 *            Configuration对象
	 * @param uri
	 *            HDFS地址
	 * @param remote
	 *            需要下载的文件的HDFS地址
	 * @param local
	 *            下载到本地目录
	 * @throws IOException
	 *             异常
	 */
	public static void download(Configuration conf, String uri, String remote,
			String local) throws IOException {
		Path path = new Path(remote);
		FileSystem fs = FileSystem.get(URI.create(uri), conf);
		fs.copyToLocalFile(path, new Path(local));
		System.out.println("download: from" + remote + " to " + local);
		fs.close();
	}

	public static void main(String[] args) throws Exception {
		String krb5File = "/usr/dac/conf/krb5.conf";
		String user = "asmp@CSVW.COM";
		String keytabPath = "/usr/dac/conf/asmp.keytab";

		Configuration conf = getConfig(krb5File, user, keytabPath);

		String URI = "hdfs://svlhdpt01-pip.csvw.com:8020";
		String remotePath = "/user/asmp/shell/pro/aftersales/dailyreport/2016-12/2016-12-31.csv";

		 getHdfsFileList(URI, remotePath, conf); 

		download(conf, URI, remotePath, "/usr/dac/download");

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Iceberg是一个开源的表格管理库,可以将数据存储在云存储中,如Hadoop HDFS、Amazon S3等,并提供了增删改查的功能。而Flink是一个开源的流处理框架,可以处理实时数据流。 要在Flink中使用Iceberg进行增删改查操作,需要使用Iceberg的Flink集成库。以下是一些示例代码来说明如何进行增删改查操作: 1. 创建Iceberg表: ```java import org.apache.flink.table.catalog.CatalogTable; import org.apache.flink.table.catalog.GenericInMemoryCatalog; import org.apache.iceberg.flink.CatalogLoader; import org.apache.iceberg.flink.TableLoader; import org.apache.iceberg.flink.TableLoaderOptions; import org.apache.iceberg.Table; import org.apache.iceberg.catalog.TableIdentifier; import org.apache.iceberg.types.Types; // 创建一个内存catalog GenericInMemoryCatalog catalog = new GenericInMemoryCatalog("my_catalog"); // 创建一个表格 CatalogTable table = new CatalogTable( TableSchema.builder() .field("id", DataTypes.INT()) .field("name", DataTypes.STRING()) .build(), CatalogTableOptions.builder() .withCatalogTableType(CatalogTableType.MANAGED) .build() ); // 注册表格到catalog catalog.createTable(new ObjectPath("default", "my_table"), table, false); // 加载catalog和table CatalogLoader catalogLoader = CatalogLoader.hive("my_catalog"); TableLoader tableLoader = TableLoader.fromCatalog(catalogLoader); Table table = tableLoader.load(TableIdentifier.of("default", "my_table")); // 添加数据到表格 DataFile file = DataFiles.builder(table.spec()) .withInputFile(new Path("/path/to/data.parquet")) .withFormat(FileFormat.PARQUET) .build(); table.newAppend().appendFile(file).commit(); // 查询表格数据 table.newScan().project("id", "name").asEnumerable().forEach(row -> { System.out.println(row.get(0) + " " + row.get(1)); }); // 删除表格 table.delete(); ``` 2. 查询Iceberg表: ```java import org.apache.flink.table.api.Table; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; import org.apache.iceberg.flink.CatalogLoader; import org.apache.iceberg.flink.TableLoaderOptions; import org.apache.iceberg.Table; import org.apache.iceberg.catalog.TableIdentifier; // 创建StreamTableEnvironment StreamTableEnvironment tEnv = StreamTableEnvironment.create(env); // 加载catalog和table CatalogLoader catalogLoader = CatalogLoader.hive("my_catalog"); TableLoaderOptions options = new TableLoaderOptions(); options.setTableIdentifier(TableIdentifier.of("default", "my_table")); Table table = TableLoader.fromCatalog(catalogLoader, options).load(); // 将Iceberg表格注册为Flink表 tEnv.createTemporaryView("my_table", table); // 查询表格数据 Table result = tEnv.sqlQuery("SELECT id, name FROM my_table WHERE id > 100"); result.toRetractStream(Row.class).print(); ``` 3. 修改Iceberg表: ```java import org.apache.iceberg.Schema; import org.apache.iceberg.Table; import org.apache.iceberg.types.Types; // 加载catalog和table CatalogLoader catalogLoader = CatalogLoader.hive("my_catalog"); TableLoaderOptions options = new TableLoaderOptions(); options.setTableIdentifier(TableIdentifier.of("default", "my_table")); Table table = TableLoader.fromCatalog(catalogLoader, options).load(); // 修改表格Schema Schema schema = new Schema( Types.NestedField.optional(1, "id", Types.IntegerType.get()), Types.NestedField.optional(2, "name", Types.StringType.get()), Types.NestedField.optional(3, "age", Types.IntegerType.get()) ); table.updateSchema().addColumn("age", Types.IntegerType.get()).commit(); // 修改表格数据 table.newUpdate() .set("age", 30) .where("id = 1") .commit(); ``` 这些示例代码演示了如何在Flink中使用Iceberg进行增删改查操作。你可以根据自己的需求来调整代码。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值