Guava Library Learning: Learning Guava Files Series (i)

Source: Internet
Author: User
Tags first string

Original address: Guava Library Learning: Learning Guava Files Series (i)

For program developers, the ability to read and write files is an important skill. But surprisingly, while Java provides a rich and robust I/O library, it is cumbersome to perform some basic file operations. But there have been some changes in Java 7, but those that use Java 6 are less fortunate. Fortunately, guava does some of the things we expect I/O libraries to do, providing a range of tools that allow us to do I/O more conveniently. In this article, we begin to learn how to use guava files for some I/O operations.

Although Java 7 has made some improvements and solved some guava minor problems, we have found that the tools provided by guava are still very useful for I/O operations. In this guava files series, we are going to learn something:

    • Uses the files class to perform basic tasks such as moving or copying files, or reading the contents of a file into a string collection

    • The Closer class, which provides a very clean way to Make sure that the closeable instance is closed correctly

    • Bytesource and Charsource classes, which provide immutable input streams (input) and read (reader)

    • Bytesink and The Charsink class, which provides immutable output streams (outputs) and write (writer)

    • Charstreams and Bytestreams classes, is read Readers, write writers , input stream inputstreams , output stream OUTPUTSTREAMS 

    • baseencoding class, Provides methods for encoding and decoding byte sequences and ASCII characters

Copying of files

The files class provides some useful ways to manipulate file objects, and for Java developers, copying one file to another is a challenging task. But in guava, let's see how to do the same with the files class:

@Testpublic void Testcopyfile () throws IOException {file original = new File ("D:\\test.txt");    File copy = new file ("D:\\test2.txt"); Files.copy (original, copy);}

Move/rename a file

Similarly,moving files in Java is as cumbersome as copying. In the guava, it is very simple, the code is as follows:

@Testpublic void Testmovefile () throws IOException {file original = new File ("D:\\test.txt");    File NewFile = new file ("D:\\test2.txt"); Files.move (original, newFile);}

Working with files like strings

There are times when we need to manipulate or use a string representation of a file. The files class provides methods to read a file into a collection of strings, return the first string of files, and read the contents of a full file into a string. The following example describes a file that is read into a string collection by calling the Files.readlines method:

 @Testpublic  void  Readfileintolistofstringstest ()  throws ioexception {    file file  = new file ("D:\\test2.txt");     list<string> expectedlines  = lists.newarraylist ("Hello world",  "This is realfighter",  "" );     list<string> readlines = files.readlines (file,             charsets.utf_8);     assertthat (Expectedlines, is (ReadLines));} 

in the example above, we used a unit test to confirm that the three lines of content read from a simple file are the same as our expectations. Line breaks in each line of content are deleted, but other whitespace characters are preserved. Files.readlines can also receiveLineprocessor Instances as additional additional parameters. Each row contains a parameter Lineprocessor.processline method, which returns a Boolean value. Lineprocessor Instances are read continuously the line in the file until the file is finished readingor the Lineprocessor.processline method returns false. Let's say we have a file that contains the following information:

    We want to extract the titles of the books in each row of data. To accomplish this task, we need to do the following for the Lineprocessor interface:

class tolistlineprocessor implements lineprocessor<list<string>> {     private static final splitter splitter = splitter.on (",");     private list<string> booktitles = lists.newarraylist ();     private static final int TITLE_INDEX = 1;      @Override     public boolean processline (string line)  throws  ioexception {        booktitles.add (Iterables.get ( Splitter.split (line),  title_index));        return true;     }     @Override     public list<string > getresult ()  {        return bookTitles;     }}

Here we will separate each row with commas, get the title of the book, be the second item in each row, and add the caption to a collection of strings. Note that we used the Iterables class and used the static Iterables.get method to get the title of the book.Processline Methodalways returns true because we need to get the book name in all the files, here is the unit test for the Lineprocessor instance:

@Testpublic void Readlineswithprocessor () throws Exception {File File = new file ("D:\\test2.txt"); list<string> expectedlines = lists.newarraylist ("Being A great Cook", "Art is Fun", "being an Architect", "H    Istory of Football "," Gardening My ");    list<string> readlines = files.readlines (file, Charsets.utf_8, New Tolistlineprocessor ()); Assertthat (Expectedlines, is (ReadLines));}

In this example, we simply get to read all the inputs, but we can easily get only n rows or filter some data through some conditions.

the hash value of the file

Generating a hash of a file in Java seems to require a lot of code manipulation, but in guava it becomes very simple. The files class has a hash method that uses the following code:

@Testpublic void Testfileshashing () throws exception{File File = new file ("D:\\test2.txt");    Hashcode hashcode = Files.hash (file, hashing.md5 ()); System.out.println (hashcode);}

In the above example, in order to use the Files.hash method, we provide the file object and the Hashfuction instance, we use a hash function that implements the MD5 algorithm, and the method returns a Hashcode object. The hash function will be introduced in the next series, so please look forward to it.

File Write

When we use the input/output stream, we often need to write code for the following steps:

    1. Open the input/output stream.

    2. Reads the bytes into/read out.

    3. After reading, make sure that all resources are closed in the finally code block.

When we have to repeat the process over and over again, it is easy to make mistakes and makes the code more and more unclear and difficult to maintain. The files class provides us with the convenience of being able to easily write/append data in a file or read the contents of a file into a byte array. Most of the code that we need to focus on to open or close a resource is simply a single line of code.

File Write and append data

An example of a simple file's write and append data, the code is as follows:

@Testpublic  void appendingwritingtofiletest ()  throws IOException {     file file = new file ("D:\\test2.txt");     file.deleteonexit ();     String hamletQuoteStart =  "To be, or not to be ";     files.write (Hamletquotestart, file, charsets.utf_8);     assertthat (Files.tostring (File, charsets.utf_8),  is (Hamletquotestart));     String hamletQuoteEnd =  ", that is the question";     Files.append (Hamletquoteend, file, charsets.utf_8);     assertthat (Files.toString (File, charsets.utf_8),  is (hamletquotestart + hamletquoteend));     string overwrite =  "Overwriting the file";     files.write ( Overwrite, file, charsetS.utf_8);     assertthat (Files.tostring (File, charsets.utf_8),  is (overwrite));} 

In this example, we use unit tests to do several things:

    1. Create a test file and make sure the file with the same name does not exist in the JVM

    2. We use the Files.write method to write a character to the file and ensure that the write succeeds

    3. We then used the Files.append method to append another character to the file, and also to confirm that the appended content already exists in the file

    4. Finally, we use the Files.write method again to overwrite the file and ensure that the file has been overwritten

Although this is a simple example, note that we wrote the file three times and we did not write any code to open or close the resource. As a result, our code becomes easy to read and, more importantly, not prone to errors.

Guava Library Learning: Learning Guava Files Series (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.