Welcome to HQ's Blog

Hello World! If you've visited this blog before, welcome back. Please help me what article do you like by give it a comment. But if you're new with this blog, please feel free to stay ahead for a shortwhile, to read my articles. I assure you will get something by read it carefully. Haha...

Ok ok... By the way, this blog belongs to me, Haqqi. Yeah, that is my nickname. If you want to know about me, please read the top sidebar titled "About Me". If you want to know MORE about me, please feel free to add my Messenger (xp_guitarist) and chat with me. I am Indonesian. My English is not so good, so please don't laugh if my 'syntax' is wrong. But sometimes I will post my blog in Bahasa Indonesia (I think most of them will).

The reason I create this blog is, I want to share everything I can share. From my experience, computer program I used, my algorithms and source codes, and some useful infos and tips. So, if you want to request something I can, feel free to ask. And if you also want to share me something, I always open my hand, haha. Anyway, WELCOME TO MY BLOG!

This site is best viewed with Mozilla Firefox with resolution 1024x800 or more

Page copy protected against web site content infringement by Copyscape

ANNOUNCEMENT!!!

This blog is dead!!! I moved it to my new blog in http://haqqi.net. Thank you for reading this blog. Hope you will read my new blog too.


Tutorial Java : File Read and Write

Jul 17, 2009

Useful Java file I/O class

Studying Java is an exciting thing. I really love coding and I am really happy to share that. After writing the Devilish Children, I was confused when writing the next game. One thing that is so important is File Input and Output. I mean, I need to know the easiest way to read and write text file using Java. After searching for the sollution, I found some easy way to do that. I just have to create a FileUtil class that has static method to read and write file. Actually, I get this code from a Game Engine called GTGE. Because GTGE is an open source project, I modified it to fulfill my requirement, added some comments, and write it to this blog.

Here is the source code of FileUtil.java class:


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;

/**
* This class has been written by Haqqi. You can
* freely use, modify, and distribute it.
* @author Haqqi
*/
public class FileUtil {
/**
* Private constructor to prevent the object creation
*/
private FileUtil() {}
/**
* 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 list = new ArrayList();
// 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 (String[])list.toArray(new String[0]);
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

The constructor is modified to be private to prevent the object creation, since all the methods is static method. Before you use fileWrite and fileRead method, you can easily set the file by using setFile method. You just need to set the relative path of the file from working directory. For example, if your woring directory is "D:\\My Java Project\TheProject", and your file is inside folder "data" and titled "My Files.my", so you just call setFile("data/My Files.my"); to get the file. Use the set file in method fileRead and FileWrite. Remember that fileRead returns an Array of String. Each index for 1 line in the file.

Ok, I hope this post will be very helpful for you. Please be free to leave a comment.

1 comments:

Anonymous said...

Certainly. It was and with me. Let's discuss this question.