番石榴文件:Java文件管理

正如我在这里这里这里这里所讨论的那样, GroovyJava SE 7都Java文件管理提供了改进。 但是,当特定的Java应用程序尚不能使用Java SE 7或Groovy进行文件管理时,仍然可以通过使用GuavaFiles类获得改进的文件管理体验。

与其他许多编程语言相比,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 获取文件的摘要的功能。 ,访问的BufferedReaderFiles.newReader(文件,字符集) ,访问的BufferedWriterFiles.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值