Статьи

Файлы Guava: Управление файлами Java

И Groovy, и Java SE 7 предоставляют улучшения для управления файлами в Java, как я обсуждал в постах здесь , здесь , здесь и здесь . Однако, когда конкретное приложение Java еще не может использовать Java SE 7 или Groovy для управления файлами, улучшенный опыт управления файлами все еще можно получить с помощью класса Files Guava .

Обработка файлов всегда была немного сложнее в Java, чем во многих других языках программирования. Java SE 7, безусловно, значительно улучшает возможности обработки файлов Java с помощью NIO.2 , но не каждый проект может использовать Java SE 7. Для тех проектов, которые не могут использовать Java SE 7, класс Files Guava является хорошим промежуточным решением для упрощения обработки файлов. , Здесь важно отметить, что Java SE 7 представляет собственный класс Files , поэтому любое использование класса Files Guava в Java SE 7 должно быть полностью ограничено, если Java-версия Files используется в том же коде. Мои примеры были написаны и построены на Java SE 7, но я избегаю использовать класс Files Java SE 7 и поэтому не должен полностью охватывать класс с одноименным названием Guava.

Создание файла

Класс Files Guava включает несколько перегруженных методов write для простой записи содержимого в файл. Следующий пример кода демонстрирует использование Files.write (byte [], File) .

Демонстрация Files.write (byte [], File)

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
<span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">/**</span> / **</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Demonstrate writing bytes to a specified file.</span> * Продемонстрировать запись байтов в указанный файл.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param fileName Name of file to be written to.</span> * @param fileName Имя файла для записи.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param contents Contents to be written to file.</span> * @param content Содержимое для записи в файл.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/</span> * /</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">public void demoFileWrite(final String fileName, final String contents)</span> public void demoFileWrite (окончательное строковое имя файла, окончательное строковое содержимое)</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(fileName, 'Provided file name for writing must NOT be null.');</span> checkNotNull (fileName, 'Предоставленное имя файла для записи НЕ должно быть нулевым.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(contents, 'Unable to write null contents.');</span> checkNotNull (содержимое, «невозможно записать нулевое содержимое.»);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File newFile = new File(fileName);</span> окончательный файл newFile = новый файл (fileName);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">try</span> пытаться</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">Files.write(contents.getBytes(), newFile);</span> Files.write (contents.getBytes (), newFile);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">catch (IOException fileIoEx)</span> поймать (IOException fileIoEx)</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">err.println( 'ERROR trying to write to file '' + fileName + '' - '</span> err.println ('ОШИБКА пытается записать в файл' '+ fileName +' '-'</span>
                    <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ fileIoEx.toString());</span> + fileIoEx.toString ());</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>

Есть несколько наблюдений, которые могут быть из этого первого примера кода, которые будут применяться ко всем другим образцам кода в этом посте. Во-первых, я использую статически импортированный класс Guava Preconditions, чтобы обеспечить простую проверку, гарантирующую, что предоставленные параметры не являются нулевыми. Вторая общая черта этого кода заключается в том, что он явно перехватывает и обрабатывает проверенное исключение IOException . Все остальные методы Files продемонстрированные в этом посте, аналогичным образом выдают это же проверенное исключение

Копирование файлов

Следующий пример демонстрирует, как легко копировать файлы, используя метод Guava’s Files.copy (File, File) (один из нескольких перегруженных методов с именем «copy»).

Демонстрация Files.copy (Файл, Файл)

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">/**</span> / **</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Demonstrate simple file copying in Guava.</span> * Продемонстрировать простое копирование файлов в Guava.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">This demonstrates one of the</span> Это демонстрирует один из</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* numerous overloaded copy methods provided by Guava's Files class.</span> * многочисленные перегруженные методы копирования, предоставляемые классом Guava's Files.</span> <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">The</span></span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* version demonstrated here copies one provided File instance to another</span> * показанная здесь версия копирует один предоставленный экземпляр файла в другой</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* provided File instance.</span> * предоставленный экземпляр файла.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param sourceFileName Name of file that is to be copied.</span> * @param sourceFileName Имя файла, который нужно скопировать.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param targetFileName Name of file that is result of file copying.</span> * @param targetFileName Имя файла, являющегося результатом копирования файла.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/</span> * /</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">public void demoSimpleFileCopy(</span> public void demoSimpleFileCopy (</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final String sourceFileName, final String targetFileName)</span> final String sourceFileName, final String targetFileName)</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(sourceFileName, 'Copy source file name must NOT be null.');</span> checkNotNull (sourceFileName, 'Копировать имя исходного файла НЕ должно быть нулевым.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(targetFileName, 'Copy target file name must NOT be null.');</span> checkNotNull (targetFileName, 'Копировать имя целевого файла не должно быть нулевым.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File sourceFile = new File(sourceFileName);</span> окончательный файл sourceFile = новый файл (sourceFileName);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File targetFile = new File(targetFileName);</span> окончательный файл targetFile = новый файл (targetFileName);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">try</span> пытаться</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">Files.copy(sourceFile, targetFile);</span> Files.copy (sourceFile, targetFile);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">catch (IOException fileIoEx)</span> поймать (IOException fileIoEx)</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">err.println(</span> err.println (</span>
             <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'ERROR trying to copy file '' + sourceFileName</span> 'ОШИБКА при попытке скопировать файл' '+ sourceFileName</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ '' to file '' + targetFileName + '' - ' + fileIoEx.toString());</span> + '' to file '' + targetFileName + '' - '+ fileIoEx.toString ());</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>


Перемещение файлов

Перемещение файлов с помощью Guava так же просто, как копирование. Метод Files.move (File, File) демонстрируется в следующем фрагменте кода.

Демонстрация файлов .move (файл, файл)

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">/**</span> / **</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Demonstrate moving a file with Guava's Files.move(File,File).</span> * Продемонстрировать перемещение файла с помощью Guava's Files.move (Файл, Файл).</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param sourceFileName Path/name of File to be moved.</span> * @param sourceFileName Путь / имя файла для перемещения.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param targetFileName Path/name of Destination of file.</span> * @param targetFileName Путь / имя пункта назначения файла.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/</span> * /</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">public void demoMove(final String sourceFileName, final String targetFileName)</span> public void demoMove (окончательное String sourceFileName, окончательное String targetFileName)</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(sourceFileName, 'Move source file name must NOT be null.');</span> checkNotNull (sourceFileName, «Переместить имя исходного файла НЕ должно быть нулевым.»);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(targetFileName, 'Move destination name must NOT be null.');</span> checkNotNull (targetFileName, «Переместить имя назначения не должно быть нулевым.»);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File sourceFile = new File(sourceFileName);</span> окончательный файл sourceFile = новый файл (sourceFileName);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File targetFile = new File(targetFileName);</span> окончательный файл targetFile = новый файл (targetFileName);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">try</span> пытаться</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">Files.move(sourceFile, targetFile);</span> Files.move (sourceFile, targetFile);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">catch (IOException fileIoEx)</span> поймать (IOException fileIoEx)</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">err.println(</span> err.println (</span>
             <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'ERROR trying to move file '' + sourceFileName</span> 'ОШИБКА при попытке переместить файл' '+ sourceFileName</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ '' to '' + targetFileName + '' - ' + fileIoEx.toString());</span> + '' to '' + targetFileName + '' - '+ fileIoEx.toString ());</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>


Сравнение файлов

Определить, являются ли два файла одинаковыми, просто с помощью метода Gauva Files.equal (File, File)

Демонстрация Files.equal (Файл, Файл)

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">/**</span> / **</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Demonstrate using Guava's Files.equal(File,File) to compare contents of</span> * Продемонстрировать использование файла Guava's Files.equal (File, File) для сравнения содержимого</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* two files.</span> * два файла.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param fileName1 Name of first file to be compared.</span> * @param fileName1 Имя первого файла для сравнения.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param fileName2 Name of second file to be compared.</span> * @param fileName2 Имя второго файла для сравнения.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/</span> * /</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">public void demoEqual(final String fileName1, final String fileName2)</span> public void demoEqual (финальная строка fileName1, финальная строка fileName2)</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(fileName1, 'First file name for comparison must NOT be null.');</span> checkNotNull (fileName1, 'Имя первого файла для сравнения НЕ должно быть нулевым.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(fileName2, 'Second file name for comparison must NOT be null.');</span> checkNotNull (fileName2, 'Второе имя файла для сравнения НЕ должно быть нулевым.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File file1 = new File(fileName1);</span> окончательный файл file1 = новый файл (fileName1);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File file2 = new File(fileName2);</span> окончательный файл file2 = новый файл (fileName2);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">try</span> пытаться</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">out.println(</span> out.println (</span>
            <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'File '' + fileName1 + '' '</span> 'File' '+ fileName1 +' ''</span>
          <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ (Files.equal(file1, file2) ? 'IS' : 'is NOT')</span> + (Files.equal (file1, file2)? 'IS': 'is NOT')</span>
          <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ ' the same as file '' + fileName2 + ''.');</span> + 'так же, как файл' '+ fileName2 +' '.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">catch (IOException fileIoEx)</span> поймать (IOException fileIoEx)</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">err.println(</span> err.println (</span>
             <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'ERROR trying to compare two files ''</span> 'ОШИБКА пытается сравнить два файла' '</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ fileName1 + '' and '' + fileName2 + '' - ' + fileIoEx.toString());</span> + fileName1 + '' и '' + fileName2 + '' - '+ fileIoEx.toString ());</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>


Трогательные файлы

Прикосновение к файлу для создания нового пустого файла или обновления временной метки существующего файла может быть легко выполнено с помощью файла Guava’s Files.touch (Файл), как показано в следующем примере кода.

Демонстрация Files.touch (Файл)

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">/**</span> / **</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Demonstrate Guava's Files.touch(File) method.</span> * Продемонстрировать метод Guava's Files.touch (File).</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param fileNameToBeTouched Name of file to be 'touch'-ed.</span> * @param fileNameToBeTouched Имя файла для редактирования.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/</span> * /</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">public void demoTouch(final String fileNameToBeTouched)</span> public void demoTouch (окончательный строковый fileNameToBeTouched)</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(fileNameToBeTouched, 'Unable to 'touch' a null filename.');</span> checkNotNull (fileNameToBeTouched, 'Невозможно "коснуться" пустого имени файла.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File fileToTouch = new File(fileNameToBeTouched);</span> окончательный файл fileToTouch = новый файл (fileNameToBeTouched);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">try</span> пытаться</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">Files.touch(fileToTouch);</span> Files.touch (fileToTouch);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">catch (IOException fileIoEx)</span> поймать (IOException fileIoEx)</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">err.println(</span> err.println (</span>
             <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'ERROR trying to touch file '' + fileNameToBeTouched</span> 'ОШИБКА при попытке прикоснуться к файлу' '+ fileNameToBeTouched</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ '' - ' + fileIoEx.toString());</span> + '' - '+ fileIoEx.toString ());</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>


Получение содержимого файла

С простотой, напоминающей расширение GDK Groovy File.getText () , Guava’s Files.toString (File, Charset) позволяет легко получать текстовое содержимое файла.

Демонстрация Files.toString (File, Charset)

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">/**</span> / **</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Demonstrate retrieving text contents of a specified file with Guava's</span> * Продемонстрировать получение текстового содержимого указанного файла с помощью Guava's</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Files.toString(File) method.</span> * Files.toString (File) метод.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param nameOfFileToGetTextFrom Name of file from which text is to be</span> * @param nameOfFileToGetTextFrom Имя файла, из которого должен быть текст</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* retrieved.</span> * восстановлено.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/</span> * /</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">public void demoToString(final String nameOfFileToGetTextFrom)</span> public void demoToString (final String nameOfFileToGetTextFrom)</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">checkNotNull(nameOfFileToGetTextFrom, 'Unable to retrieve text from null.');</span> checkNotNull (nameOfFileToGetTextFrom, 'Невозможно получить текст с нуля.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File sourceFile = new File(nameOfFileToGetTextFrom);</span> окончательный файл sourceFile = новый файл (nameOfFileToGetTextFrom);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">try</span> пытаться</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final String fileContents = Files.toString(sourceFile, Charset.defaultCharset());</span> final String fileContents = Files.toString (sourceFile, Charset.defaultCharset ());</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">out.println(</span> out.println (</span>
             <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'Contents of File '' + nameOfFileToGetTextFrom</span> «Содержимое файла» + nameOfFileToGetTextFrom</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ '' are: ' + fileContents);</span> + '' являются: '+ fileContents);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">catch (IOException fileIoEx)</span> поймать (IOException fileIoEx)</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">err.println(</span> err.println (</span>
             <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'ERROR trying to get text contents of file ''</span> 'ОШИБКА при попытке получить текстовое содержимое файла' '</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ nameOfFileToGetTextFrom + '' - ' + fileIoEx.toString());</span> + nameOfFileToGetTextFrom + '' - '+ fileIoEx.toString ());</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>


Создание временного каталога

Guava упрощает создание временного каталога с помощью Files.createTempDir () .

Демонстрация Files.createTempDir ()

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
<span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">/**</span> / **</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Demonstrate Guava's Files.createTempDir() method for creating a temporary</span> * Продемонстрировать метод Guava's Files.createTempDir () для создания временного</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* directory.</span> * каталог.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/</span> * /</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">public void demoTemporaryDirectoryCreation()</span> public void demoTeilitaryDirectoryCreation ()</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File newTempDir = Files.createTempDir();</span> final File newTempDir = Files.createTempDir ();</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">try</span> пытаться</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">out.println(</span> out.println (</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'New temporary directory is '' + newTempDir.getCanonicalPath() + ''.');</span> 'Новый временный каталог:' '+ newTempDir.getCanonicalPath () +' '.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">catch (IOException ioEx)</span> поймать (IOException ioEx)</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">err.println('ERROR: Unable to create temporary directory - ' + ioEx.toString());</span> err.println ('ОШИБКА: невозможно создать временный каталог -' + ioEx.toString ());</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>

Я не привожу здесь пример кода, но стоит отметить, что Guava предоставляет удобный метод для создания нового каталога, который будет содержать все необходимые новые родительские каталоги с его методом Files.createParentDirs (File) .

Получение содержимого файла в виде строк

Есть моменты, когда наиболее удобно получить содержимое файла в виде последовательности строк, чтобы каждая строка могла быть обработана. Обычно это делается в Groovy с перегруженными версиями readLines () и eachLine () . Guava обеспечивает аналогичную функциональность Groovy File.readLines() с его методом Files.readLines (File, Charset) . Это продемонстрировано в следующем примере кода.

Демонстрация Files.readLines (File, Charset)

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">/**</span> / **</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Demonstrate extracting lines from file.</span> * Продемонстрировать извлечение строк из файла.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param fileName Name of file from which lines are desired.</span> * @param fileName Имя файла, из которого нужны строки.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/</span> * /</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">public void demoRetrievingLinesFromFile(final String fileName)</span> public void demoRetrievingLinesFromFile (окончательный String fileName)</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File file = new File(fileName);</span> окончательный файл file = новый файл (fileName);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">try</span> пытаться</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final List<String> lines = Files.readLines(file, Charset.defaultCharset());</span> окончательный список <String> lines = Files.readLines (file, Charset.defaultCharset ());</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">for (final String line : lines)</span> для (последняя строковая строка: строки)</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">out.println('>> ' + line);</span> out.println ('>>' + строка);</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">catch (IOException ioEx)</span> поймать (IOException ioEx)</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">err.println(</span> err.println (</span>
             <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'ERROR trying to retrieve lines from file ''</span> 'ОШИБКА пытается получить строки из файла' '</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ fileName + '' - ' + ioEx.toString());</span> + fileName + '' - '+ ioEx.toString ());</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>

Другая перегруженная версия readLines интересна тем, что позволяет указывать обратный вызов LineProcessor для прекращения возврата строк раньше, чем конец файла.

Первая строка чтения файла

Я сталкивался с многочисленными ситуациями, в которых было полезно читать только первую строку файла. Эта первая строка может сообщить моему коду, какой тип сценария выполняется, предоставить информацию о прологе XML или другие интересные обзорные данные содержимого файла. Guava позволяет легко получить только первую строку с помощью метода Files.readFirstLine (File, Charset) . Это продемонстрировано в следующем листинге кода.

Демонстрация файлов .readFirstLine (File, Charset)

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">/**</span> / **</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* Demonstrate extracting first line of file.</span> * Продемонстрировать извлечение первой строки файла.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*</span> *</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">* @param fileName File from which first line is to be extracted.</span> * @param fileName Файл, из которого должна быть извлечена первая строка.</span>
   <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">*/</span> * /</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">public void demoRetrievingFirstLineFromFile(final String fileName)</span> public void demoRetrievingFirstLineFromFile (окончательный строковый fileName)</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final File file = new File(fileName);</span> окончательный файл file = новый файл (fileName);</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">try</span> пытаться</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">final String line = Files.readFirstLine(file, Charset.defaultCharset());</span> окончательная строка String = Files.readFirstLine (file, Charset.defaultCharset ());</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">out.println('First line of '' + fileName + '' is '' + line + ''.');</span> out.println ('Первая строка' '+ fileName +' '- это' '+ line +' '.');</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">catch (IOException fileIoEx)</span> поймать (IOException fileIoEx)</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">{</span> {</span>
        <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">err.println(</span> err.println (</span>
             <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">'ERROR trying to retrieve first line of file ''</span> 'ОШИБКА пытается получить первую строку файла' '</span>
           <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">+ fileName + '' - ' + fileIoEx.toString());</span> + fileName + '' - '+ fileIoEx.toString ());</span>
     <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>
  <span class="notranslate" onmouseover="_tipon(this)" onmouseout="_tipoff()"><span class="google-src-text" style="direction: ltr; text-align: left">}</span> }</span>


Там намного больше

Хотя в этом посте я обсудил и продемонстрировал несколько полезных методов Files , у класса есть еще много чего предложить. Некоторые из них включают возможность добавления к существующему файлу с помощью Files.append (CharSequence, File, Charset) , получение контрольной суммы файла с помощью Files.getChecksum (File, Checksum) , получение дайджеста файла с помощью Files.getDigest (File, MessageDigest) ) , доступ к BufferedReader с помощью Files.newReader (File, Charset) , доступ к BufferedWriter с помощью Files.newWriter (File, Charset) и доступ к MappedByteBuffer, сопоставленному с базовым файлом через перегруженные методы Files.map .

Вывод

Обработка файлов в Java намного проще и удобнее с классом файлов Guava. Guava обеспечивает удобство обработки файлов в приложениях Java, которые не могут использовать удобство работы с файлами в Groovy или Java SE 7.

Приятного кодирования и не забудьте поделиться!

Ссылка: Управление файлами в Java с классом файлов Guava от нашего партнера JCG Дастина Маркса в блоге Inspired by Actual Events .