Sunday, August 01, 2010

Java Tutorial – Write and Read File

Repost from my previous blog, about Java tutorial.

This post is similar with my post before

Inspired by Eko with his USU Library, now I am creating my own Java library. Of course, I will make it open source, as soon as I think it is finished with version 1.0. Hope that I will focus in this project. I think you who are a programmer should make your own library too. Because it will be useful whenever you get a project, and it will be your trademark. You know, although you decide that your library will become open source, the real author is you. So the only one who know most of your program is YOU. Don’t afraid to be open source.

This is my first Java tutorial in this blog. It’s about one of Java cores, reading and writing into a file. At first, when still newbie in Java, I was confused how to do this thing. Luckily, when reading GTGE, I found a class that is useful for this task. I learnt from it and make my own FileUtil class. Here it is, you can analyze the code.

/**
 * DO NOT REMOVE THIS LICENSE
 *
 * This source code is created by Muhammad Fauzil Haqqi.
 * You can use and modify this source code freely but
 * you are forbidden to change or remove this license.
 *
 * Nick  : Haqqi
 * YM    : xp_guitarist
 * Email : fauzil.haqqi@gmail.com
 * Blog  : http://www.fauzilhaqqi.net
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 *
 * @author Haqqi
 */
public class FileUtil {
  // *******variables area****** //

  // *****constructors area***** //
  /**
   * To prevent the creation of object
   */
  private FileUtil() {
  }

  // ********methods area******* //
  /**
   * Set the file based on relative path
   * @param filePath Path of the file
   * @return Generated file
   */
  public static File setFile(String filePath) {
    // create new file object
    File file = null;
    // getting the path from working directory
    // you can check the directory by printing it
    String path = System.getProperty("user.dir")
        + File.separatorChar + filePath;
    try {
      // construct the file based on the path
      file = new File(path);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // if file is not found, then throw exception
    if (file == null) {
      throw new RuntimeException();
    }
    return file;
  }

  /**
   * Write an Array of String into a file. The written
   * file will be just like a text file.
   * @param text Array of String that want to be written
   * @param file File
   * @return true if success and false if not
   */
  public static boolean fileWrite(String[] text, File file) {
    try {
      // create buffer
      BufferedWriter out = new BufferedWriter(new FileWriter(file));
      PrintWriter writeOut = new PrintWriter(out);
      // writing text to file
      for (int i = 0; i < text.length; i++) {
        writeOut.println(text[i]);
      }
      // close the writer
      writeOut.close();
      return true;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
  }

  /**
   * Read file from a file
   * @param file
   * @return
   */
  public static String[] fileRead(File file) {
    try {
      // buffered reader
      BufferedReader readIn = new BufferedReader(new FileReader(file));
      // ArrayList to store the string each line
      ArrayList<String> list = new ArrayList<String>();
      // Temporarily object
      String data;
      // Read each line until end of line
      while ((data = readIn.readLine()) != null) {
        list.add(data);
      }
      // closing reader
      readIn.close();
      // return as Array of String
      return list.toArray(new String[0]);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
}

Using comments I wrote above, you can study how it works by yourself. There are 3 static methods, setFile(), fileWrite(), and fileRead(). The most important thing about reading and writing a file is the location of the file. Using setFile() method, you can easily locate it based on your working directory. After the file is set, you can easily read and write it using another methods above. I think, because my code is already in form of a class, you don’t need to copy several lines and paste into your class. You can copy the whole class and place it in any package of your project.

Oke, I hope this post will help you out from your problem. Please be free to leave a comment. Lets code in Java!!! :D

Bahasa keywords: Tutorial Java membaca dan menulis file


  • than'ks info...semoga manfaat kang...
  • Iya, sama-sama bro...
    Moga bermanfaat buat game loe...
blog comments powered by Disqus
 

My Tweets

Banners

Tag Cloud

Get Adobe Flash playerPlugin by wpburn.com wordpress themes