通過FSDataOutputStream向HDFS上寫數據
阿新 • • 發佈:2018-01-01
on() file finally enable dfs ack 建立 row path
FSDataOutputStream,這個類重載了很多write方法,用於寫入很多類型的數據:比如字節數組,long,int,char等等。
像FSDataInputStream一樣,要獲得FSDataOutputStream的實例,必須通過FileSystem該類來和HDFS建立連接,然後通過路徑返回FSDataOutputStream實例。
FileSystem返回FSDataOutputStream實例的方法有兩組
1.create(Path p)函數,創建一個空文件,然後可以向該文件順序寫入
2.append(Path p)函數,打開一個已有文件,並最做文件末尾追加數據
FileSystemUtil
public class FileSystemUtil { private static FileSystem fileSystem;
//代碼中Kerberos認證根據自己環境替換即可 public synchronized static FileSystem getFileSystem() throws IOException{ if(fileSystem==null){ Configuration conf=new Configuration(); conf.set("fs.defaultFS", "hdfs://host12.master.cluster.enn.cn:8020"); conf.set("dfs.client.block.write.replace-datanode-on-failure.policy" ,"NEVER" ); conf.set("dfs.client.block.write.replace-datanode-on-failure.enable" ,"true" ); KerberosClient.login(Constants.Kerberos_USER_NAME, Constants.Kerberos_KEYTAB_FILE); fileSystem=FileSystem.get(conf); }return fileSystem; } public synchronized static void shutdown(){ if(fileSystem!=null){ try { fileSystem.close(); fileSystem=null; } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) throws Exception { System.out.println(FileSystemUtil.getFileSystem()); } }
FSDataOutputStreamTest
public class FSDataOutputStreamTest{ private static final Logger LOGGER = LoggerFactory.getLogger(Test.class); private static void hfdsAppendData() { String filePath = "/user/hive/warehouse/test.db/t_test/day=2017-11-29/hour=16/backup_ycgqh"; FileSystem fileSystem = null; FSDataOutputStream fileOutputStream = null; Path hdfsPath = new Path(filePath); try { fileSystem=FileSystemUtil.getFileSystem(); if (!fileSystem.exists(hdfsPath)) { fileOutputStream = fileSystem.create(hdfsPath,false); }else{ fileOutputStream = fileSystem.append(hdfsPath); } fileOutputStream.writeUTF(""); } catch (IOException e) { e.printStackTrace(); }finally { if(fileOutputStream!=null){ try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } FileSystemUtil.shutdown(); } } } }
通過FSDataOutputStream向HDFS上寫數據