public class HdfsFileTools { public static FileSystem fs ; private static void init(String url,String user) throws IOException { Configuration config = new Configuration(); config.set("fs.defaultFS", url); try { fs = FileSystem.get(URI.create(url), config,user); } catch (InterruptedException e) { e.printStackTrace(); } } public static void appendToHdfsFile(String pathString,String contens) throws IOException{ FSDataOutputStream out; Configuration conf = new Configuration(); init("hdfs://SANDBOX-HADOOP-01.whh.net:8022","bigdata"); Path path = new Path(pathString); if (fs.exists(path)) { out = fs.append(path); } else { out = fs.create(path); } System.out.println(contens); //out.writeChars(contens); // out.writeBytes(contens); // out.writeUTF(contens); out.write(contens.getBytes()); fs.close(); }
我說幾點注意事項: 一、appendToHdfsFile的功能是寫HDFS文件,當有文件存在的時候追加;不存在的時候是新建文件;(要注意文件的權限問題)app
二、寫中文的時候只有FSDataOutputStream.writeUTF()方法能寫,可是會在文本前面加2個字節的內容,因此用out.write(contens.getBytes())方法代替;如下是詳細解說:編碼
2.1 在writeBytes(String s)這個方法上。url
JAVA中的char是16位的,一個char存儲一箇中文字符,直接用writeBytes方法轉換會變爲8位,直接致使高8位丟失。從而致使中文亂碼。.net
解決方法:code
現轉換爲字節組,再write寫入流。方法以下:字符串
原方法:get
out.writeBytes(string());string
新方法:it
out.write(string.getBytes());io
2.2 writeUTF()寫出一個UTF-8編碼的字符串前面會加上2個字節的長度標識,以標識接下來的多少個字節是屬於本次方法所寫入的字節數。