2015-04-23 172 views
0

我正在通過java從本地讀取Snappy Compressed file閱讀Snappy壓縮文件時出錯

File snappyFile = new File(fileName); 
Configuration conf = new Configuration();    
CompressionCodec codec = (CompressionCodec) 
ReflectionUtils.newInstance(SnappyCodec.class, conf); 
FileInputStream is2 = new FileInputStream(snappyFile); 
CompressionInputStream cis = codec.createInputStream(is2); 
BufferedReader cr = new BufferedReader(new InputStreamReader(cis)); 

我的代碼是在ReflectionUtils.newInstance

Exception in thread "main" java.lang.RuntimeException: java.lang.NoSuchMethodException: org.xerial.snappy.SnappyCodec.<init>() 
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:128) 
    at org.finra.oats.AWS.AWSnappyRead.run(AWSnappyRead.java:64) 
    at org.finra.oats.AWS.AWSnappyRead.main(AWSnappyRead.java:48) 
Caused by: java.lang.NoSuchMethodException: org.xerial.snappy.SnappyCodec.<init>() 
    at java.lang.Class.getConstructor0(Class.java:2849) 
    at java.lang.Class.getDeclaredConstructor(Class.java:2053) 
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:122) 
    ... 2 more 

越來越例外是不是因爲版本不匹配的問題。我正在使用snappy 1.1.1.2版本

+0

從你的問題和提供的statcktrace中,你不是很清楚你想實現什麼。你想從文件系統讀取一個Snappy壓縮文件嗎? – SubOptimal

+0

你應該改說你的問題。似乎您嘗試讀取Hadoop序列文件。也許這個線程[讀寫使用Hadoop 2.0 Apis序列文件](http://stackoverflow.com/questions/16070587)可以幫助你。 – SubOptimal

+0

我已經發布了它[鏈接](http://stackoverflow.com/questions/29816067/how-to-read-snappy-compressed-file-from-s3-in-java)。你可以參考鏈接來得到一個簡要的想法。 – salmanbw

回答

1

要讀取和寫入Snappy壓縮文件,您可以使用提供的SnappyInputStream/SnappyOutputStream類。

String fileName = "foo.snap"; 

// write a snappy compressed file 
try (OutputStream os = new SnappyOutputStream(new FileOutputStream(fileName))) { 
    os.write("Hello Snappy-World".getBytes(Charset.defaultCharset())); 
} 

// read a snappy compressed file 
try (InputStream is = new SnappyInputStream(new FileInputStream(fileName))) { 
    byte[] bytes = new byte[100]; 
    is.read(bytes); 
    System.out.println(new String(bytes, Charset.defaultCharset())); 
} 

// check if the file is compressed with the snappy algorithm 
try (InputStream is = new FileInputStream(fileName)) { 
    SnappyCodec readHeader = SnappyCodec.readHeader(is); 
    if (readHeader.isValidMagicHeader()) { 
     System.out.println("is a Snappy compressed file"); 
     System.out.printf("%s: %d%n%s: %d%n", 
       "compatible version", readHeader.compatibleVersion, 
       "version", readHeader.version 
     ); 
    } else { 
     System.out.println("is not a Snappy compressed file");     
    } 
} 
+0

是SubOptimal,我想從文件系統讀取一個Snappy壓縮文件。我試過你的代碼,但我得到這個錯誤。 java.io.IOException:FAILED_TO_UNCOMPRESS(5) at org.xerial.snappy.SnappyNative.throw_error(SnappyNative.java:84) – salmanbw

+0

@ user3375762可能是不同的原因。該文件未用Snappy壓縮或已損壞。你能發送前16個字節的hexdump嗎? – SubOptimal

+0

@ user3375762這看起來不像一個活潑的壓縮文件。快速壓縮文件的魔頭被定義爲:MAGIC_HEADER = new byte [] {-126,'S','N','A','P','P','Y',0};' – SubOptimal