Powered by Blogger.

100 Java - Java Read File Line by Line in Java Program

Introduction:

This article shows how to cache files in Java in order to increase application performance. It discusses an algorithm for caching the file, a data structure for holding the cached content and a cache API for storing cached files.

File in Java:

To access a physical file we have to create a File object, which contains the address and name of the file. The FileReader class uses to read characters from a file and the FileWriter class uses to write characters to a file. The PrintWriter class is used the print() and println() methods.

Caching Files in Java:

Reading files from the disk can be slow, especially when an application reads the same file many times. Caching solves this problem by keeping frequently accessed files in memory. This allows the application to read the content of the from the fast local memory instead of the slow hard drive. Design for caching a file in Java includes three elements:

    1. An algorithm for caching the file
    2. A data structure for holding the cached content
    3. A cache API for storing cached files

Algorithm for Caching Files:-

A general algorithm for caching a file must account for file modifications and consists of the following steps:

    1. Get a value from the cache using a fully qualified file path as a key.
    2. If a key is not found, read the file content and put it to the cache.
    3. If the key is found, check if a timestamp of the cached content matches the file timestamp.
    4. If the timestamps are equal, return the cached content.
    5. If the timestamps are not equal, refresh the cache by reading the file and putting it into the cache.

Java Code for Caching Files:-

This article assumes that the file being cached is a text file. A code fragment below implements the caching algorithm for text files:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import cacheonix.Cacheonix;
import cacheonix.cache.Cache;
import com.cacheonix.examples.cache.file.cache.data.grid.TextFile;

/**
 * An application demonstrating an application-level file cache.
 */
public class ApplicationFileCacheExample {

   /**
    * Gets a file content from the cache ant prints it in the standard output.
    *
    * @param args arguments
    * @throws IOException if an I/O error occured.
    */
   public static void main(String[] args) throws IOException {

      // Replace the file name with an actual file name
      String pathName = "test.file.txt";

      ApplicationFileCacheExample fileCacheExample = new ApplicationFileCacheExample();
      String fileFromCache = fileCacheExample.getFileFromCache(pathName);
      System.out.print("File content from cache: " + fileFromCache);
   }

   /**
    * Retrieves a file from a cache. Puts it into the cache if it's not cached yet.
    *
    * This method demonstrates a typical flow an application must follow to cache a file
    * and to get it from the cache. As you can see, the application is pretty involved
    * in maintaining the cache. It must read the file, check the the timestamps and update
    * the cache if its content is stale.
    *
    * @param pathName a file path name.
    * @return a cached file content or null if file not found
    * @throws IOException if an I/O error occurred.
    */

   public String getFileFromCache(String pathName) throws IOException {

      // Get cache
      Cacheonix cacheonix = Cacheonix.getInstance();

      Cache<String, TextFile> cache = cacheonix.getCache("application.file.cache");

      // Check if file exists
      File file = new File(pathName);
      if (!file.exists()) {

         // Invalidate cache
         cache.remove(pathName);

         // Return null (not found)
         return null;
      }

      // Get the file from the cache
      TextFile textFile = cache.get(pathName);

      // Check if the cached file exists
      if (textFile == null) {

         // Not found in the cache, put in the cache

         textFile = readFile(file);

         cache.put(pathName, textFile);
      } else {

         // Found in cache, check the modification time stamp

         if (textFile.getLastModified() != file.lastModified()) {

            // Update cache

            textFile = readFile(file);

            cache.put(pathName, textFile);
         }
      }

      return textFile.getContent();
   }

   /**
    * Reads a file into a new TextFile object.
    *
    * @param file the file to read from.
    * @return a new TextFile object.
    * @throws IOException if an I/O error occurred.
    */

   private static TextFile readFile(File file) throws IOException {

      // Read the file content into a StringBuilder
      char[] buffer = new char[1000];
      FileReader fileReader = new FileReader(file);
      StringBuilder fileContent = new StringBuilder((int) file.length());

      for (int bytesRead = fileReader.read(buffer); bytesRead != -1; ) {
         fileContent.append(buffer, 0, bytesRead);
      }

      // Close the reader
      fileReader.close();

      // Create CachedTextFile object
      TextFile textFile = new TextFile();
      textFile.setContent(fileContent.toString());
      textFile.setLastModified(file.lastModified());

      // Return the result
      return textFile;
   }
}

Related Tags for Java Read File Line by Line-Java:

java, c, string, mac, com, file, unicode, orm, data, form, utf-8, application, strings, input, io, types, format, output, streams, type, stream, system, number, read, transform, write, open, app, if, for, primitive, transformation, company, to, information, ci, ndepend, e, il, safe, it, doc, can, machine, li, mit, put, specification, use, pe, modification, im, from, in, mod, utf, rm, info, cs, m, nt, out, tr, nic, min, ca, min, nic, j, ad, es, spec, td, em, end, pen, ico, me, modi, pp, pan, cat, fs, do, sys, rel, s, sp, ee, at, any, late, is, ha, inf, iv, pre, erl, erl, ea, and, ar, cod, code, str, specific, tf, repr, sa, saf, sli, va, uses, underlying, ucs, s, s, ri, ring, th, av, st, chi, 6, ati, ap, af, hat, fe, inform, informat, ica, ica, pl, pr, mina, mi, nd, ode, on, om, o, np

1 comment:

  1. I really enjoy the blog.Much thanks again. Really Great.
    Very informative article post. Really looking forward to read more. Will read on…


    oracle online training
    sap fico online training
    dotnet online training
    qa-qtp-software-testing-training-tutorial

    ReplyDelete