有用過Java I/O 的人應該都會覺得很難用又很不直觀,每次都要把InuptStream和OutputStream導來導去,更不用說還要處理一堆Error Handling,真的很麻煩....
下面是用Java原生API去處理File I/O的範例
public static void writeAllText( File file, String contents ) throws FileNotFoundException, IOException { if( file == null ) { throw new IllegalArgumentException( "File should not be null" ); } if( !file.exists() ) { throw new FileNotFoundException( "File does not exist: " + file ); } if( !file.isFile() ) { throw new IllegalArgumentException( "Should not be a directory: " + file ); } if (!file.canWrite()) { throw new IllegalArgumentException( "File cannot be written: " + file ); } // FileWriter always assumes default encoding is OK Writer output = new BufferedWriter( new FileWriter( file ) ); try { output.write( contents ); } finally { output.close(); } }
但是如果改成用Apache Jakarta Commons 來寫呢?程式碼就可以精簡成下面這樣
String testData = "test data"; try { FileUtils.writeStringToFile( new File( "/tmp/test.txt" ), testData, "UTF-8" ); } catch( IOException e ) { e.printStackTrace(); }
當然Guava 也有提供類似的功能
String testData = "test data"; try { Files.write( testData , new File( "/tmp/temp.txt"), Charsets.UTF_8 ); } catch( IOException e ) { e.printStackTrace(); }
所以好的Utility Library 帶你上天堂,請愛用Google Guava I/O....
Reference:
[1] Java I/O Tutorial
沒有留言:
張貼留言