與其他許多編程語言相比,Java中的文件處理似乎總是有些困難。 Java SE 7當然可以通過NIO.2極大地提高Java的文件處理能力 ,但是并不是每個項目都可以使用Java SE7。對于那些不能使用Java SE 7的項目,Guava的Files
類是一個很好的中間解決方案,可以更輕松地處理文件。 這里需要特別注意的是,Java SE 7引入了自己的Files類 ,因此,如果在同一代碼中使用Files
的Java版本,則Java SE 7中對Guava的Files
類的任何使用都必須完全作用域。 我的示例是用Java SE 7編寫和構建的,但是我避免使用Java SE 7的Files
類,因此不需要完全限定Guava的同名類。
文件創建
Guava的Files
類包含幾個重載的write
方法,可輕松地將內容寫入文件。 下一個代碼示例演示如何使用Files.write(byte [],File) 。
演示Files.write(byte [],File)
/*** Demonstrate writing bytes to a specified file.* * @param fileName Name of file to be written to.* @param contents Contents to be written to file.*/public void demoFileWrite(final String fileName, final String contents){checkNotNull(fileName, 'Provided file name for writing must NOT be null.');checkNotNull(contents, 'Unable to write null contents.');final File newFile = new File(fileName);try{Files.write(contents.getBytes(), newFile);}catch (IOException fileIoEx){err.println( 'ERROR trying to write to file '' + fileName + '' - '+ fileIoEx.toString());}}
從第一個代碼示例中可以得到一些觀察結果,它們將適用于本文中的所有其他代碼示例。 首先,我利用靜態導入的Guava Preconditions類來進行輕松檢查,以確保所提供的參數不為null。 該代碼的第二個共同特征是它顯式捕獲并“處理”已檢查的異常IOException 。 本文中演示的所有其他Files
方法類似地引發相同的檢查異常。
文件復制
下一個示例演示使用Guava的Files.copy(File,File)方法(名稱為“ copy”的幾種重載方法之一)復制文件非常容易。
演示Files.copy(File,File)
/*** Demonstrate simple file copying in Guava. This demonstrates one of the* numerous overloaded copy methods provided by Guava's Files class. The* version demonstrated here copies one provided File instance to another* provided File instance.* * @param sourceFileName Name of file that is to be copied.* @param targetFileName Name of file that is result of file copying.*/public void demoSimpleFileCopy(final String sourceFileName, final String targetFileName){checkNotNull(sourceFileName, 'Copy source file name must NOT be null.');checkNotNull(targetFileName, 'Copy target file name must NOT be null.');final File sourceFile = new File(sourceFileName);final File targetFile = new File(targetFileName);try{Files.copy(sourceFile, targetFile);}catch (IOException fileIoEx){err.println('ERROR trying to copy file '' + sourceFileName+ '' to file '' + targetFileName + '' - ' + fileIoEx.toString());}}
文件移動
使用番石榴移動文件就像復制一樣容易。 下一個代碼段中演示了Files.move(File,File)方法。
演示Files.move(File,File)
/*** Demonstrate moving a file with Guava's Files.move(File,File).* * @param sourceFileName Path/name of File to be moved.* @param targetFileName Path/name of Destination of file.*/public void demoMove(final String sourceFileName, final String targetFileName){checkNotNull(sourceFileName, 'Move source file name must NOT be null.');checkNotNull(targetFileName, 'Move destination name must NOT be null.');final File sourceFile = new File(sourceFileName);final File targetFile = new File(targetFileName);try{Files.move(sourceFile, targetFile);}catch (IOException fileIoEx){err.println('ERROR trying to move file '' + sourceFileName+ '' to '' + targetFileName + '' - ' + fileIoEx.toString());}}
比較文件
使用Gauva Files.equal(File,File)方法可以直接確定兩個文件是否相同
演示Files.equal(File,File)
/*** Demonstrate using Guava's Files.equal(File,File) to compare contents of* two files.* * @param fileName1 Name of first file to be compared.* @param fileName2 Name of second file to be compared.*/public void demoEqual(final String fileName1, final String fileName2){checkNotNull(fileName1, 'First file name for comparison must NOT be null.');checkNotNull(fileName2, 'Second file name for comparison must NOT be null.');final File file1 = new File(fileName1);final File file2 = new File(fileName2);try{out.println('File '' + fileName1 + '' '+ (Files.equal(file1, file2) ? 'IS' : 'is NOT')+ ' the same as file '' + fileName2 + ''.');}catch (IOException fileIoEx){err.println('ERROR trying to compare two files ''+ fileName1 + '' and '' + fileName2 + '' - ' + fileIoEx.toString());}}
接觸文件
可以使用Guava的Files.touch(File)輕松完成觸摸文件以創建新的空文件或更新現有文件上的時間戳的操作 ,如下面的代碼示例所示。
演示Files.touch(File)
/*** Demonstrate Guava's Files.touch(File) method.* * @param fileNameToBeTouched Name of file to be 'touch'-ed.*/public void demoTouch(final String fileNameToBeTouched){checkNotNull(fileNameToBeTouched, 'Unable to 'touch' a null filename.');final File fileToTouch = new File(fileNameToBeTouched);try{Files.touch(fileToTouch);}catch (IOException fileIoEx){err.println('ERROR trying to touch file '' + fileNameToBeTouched+ '' - ' + fileIoEx.toString());}}
檢索文件內容
通過使人聯想到Groovy的GDK擴展File.getText() ,番石榴的Files.toString(File,Charset)使得檢索文件的文本內容變得容易。
演示Files.toString(File,Charset)
/*** Demonstrate retrieving text contents of a specified file with Guava's * Files.toString(File) method.* * @param nameOfFileToGetTextFrom Name of file from which text is to be* retrieved.*/public void demoToString(final String nameOfFileToGetTextFrom){checkNotNull(nameOfFileToGetTextFrom, 'Unable to retrieve text from null.');final File sourceFile = new File(nameOfFileToGetTextFrom);try{final String fileContents = Files.toString(sourceFile, Charset.defaultCharset());out.println('Contents of File '' + nameOfFileToGetTextFrom+ '' are: ' + fileContents);}catch (IOException fileIoEx){err.println('ERROR trying to get text contents of file ''+ nameOfFileToGetTextFrom + '' - ' + fileIoEx.toString());}}
臨時目錄創建
Guava使使用Files.createTempDir()生成臨時目錄變得容易。
演示Files.createTempDir()
/*** Demonstrate Guava's Files.createTempDir() method for creating a temporary* directory.*/public void demoTemporaryDirectoryCreation(){final File newTempDir = Files.createTempDir();try{out.println('New temporary directory is '' + newTempDir.getCanonicalPath() + ''.');}catch (IOException ioEx){err.println('ERROR: Unable to create temporary directory - ' + ioEx.toString());}}
我在這里沒有提供代碼示例,但是值得注意的是,Guava提供了一種方便的方法來創建新目錄,該方法將使用其Files.createParentDirs(File)方法創建所有必需的新父目錄。
以行的形式檢索文件的內容
有時最方便的是將文件的內容作為一系列的行來獲取,以便可以處理每一行。 在Groovy中,通常使用readLines()和eachLine()的重載版本來完成此操作。 番石榴通過其Files.readLines(File,Charset)方法提供了與Groovy的File.readLines()
類似的功能。 在下面的代碼示例中對此進行了演示。
演示Files.readLines(File,Charset)
/*** Demonstrate extracting lines from file.* * @param fileName Name of file from which lines are desired.*/public void demoRetrievingLinesFromFile(final String fileName){final File file = new File(fileName);try{final List<String> lines = Files.readLines(file, Charset.defaultCharset());for (final String line : lines){out.println('>> ' + line);}}catch (IOException ioEx){err.println('ERROR trying to retrieve lines from file ''+ fileName + '' - ' + ioEx.toString());}}
readLines
的另一個重載版本很有趣,因為它允許指定LineProcessor回調以終止比文件結尾更早的行返回。
讀取文件的第一行
我遇到了無數情況,其中僅讀取文件的第一行很有用。 第一行可以告訴我的代碼,什么類型的腳本正在運行,提供XML序言信息或文件內容的其他有趣概述數據。 Guava使使用Files.readFirstLine(File,Charset)方法僅檢索第一行變得容易。 下一個代碼清單對此進行了演示。
演示Files.readFirstLine(File,Charset)
/*** Demonstrate extracting first line of file.* * @param fileName File from which first line is to be extracted.*/public void demoRetrievingFirstLineFromFile(final String fileName){final File file = new File(fileName);try{final String line = Files.readFirstLine(file, Charset.defaultCharset());out.println('First line of '' + fileName + '' is '' + line + ''.');}catch (IOException fileIoEx){err.println('ERROR trying to retrieve first line of file ''+ fileName + '' - ' + fileIoEx.toString());}}
還有更多
盡管我在本文中討論并演示了幾個有用的Files方法,但該類還有很多其他提供。 其中一些功能包括使用Files.append(CharSequence,File,Charset)附加到現有文件的功能,使用Files.getChecksum(File,Checksum)獲取文件的校驗和 ,使用Files.getDigest(File,MessageDigest )獲取文件的摘要的功能。 ) ,訪問的BufferedReader與Files.newReader(文件,字符集) ,訪問的BufferedWriter與Files.newWriter(文件,字符集) ,和訪問MappedByteBuffer通過重載映射到一個基礎文件Files.map方法。
結論
使用Guava的Files類,用Java處理文件更加容易和方便。 Guava為無法利用Groovy或Java SE 7的文件處理便利的Java應用程序帶來了文件處理便利。
祝您編程愉快,別忘了分享!
參考:來自JCG合作伙伴 Dustin Marx的Guava的Files類中的Java文件管理, 來自Inspired by Actual Events博客。
翻譯自: https://www.javacodegeeks.com/2012/09/guava-files-java-file-management.html