Tuesday, December 13, 2011

File Operations Example in JAVA


File Operations
package fileOperations;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
 * @author glakshmanan Nov 21st 2011
 */
public class fileOperations {

static Logger log = Logger.getLogger(fileOperations.class);
static final String fileName = "/home/glakshmanan/fileOperations.csv";

/**
*
*/
public fileOperations() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
createFileIfNoExists();
writeDataInFile();
readDataFromFile();
deleteFileIfExist();

}

private static void deleteFileIfExist() {
new File(fileName).delete();
log.info("File Deleted Successfully");
}

private static void readDataFromFile() {
if (new File(fileName).exists()) {
FileReader fileReader = null;
try {
fileReader = new FileReader(fileName);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(fileReader);
try {
String text;
while ((text = br.readLine()) != null) {
log.info("Data from File : " + text);
}
} catch (IOException e) {
log.info("File Reader error" + e.getMessage());
}
}
}

private static void writeDataInFile() {
try {
if (new File(fileName).exists()) {
FileWriter fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw);
String[] testArr = { "Gubs", "Kavitha", "Sai" };
for (String test : testArr) {
bw.write("Testing FileWritter : " + test + "\n");
}
bw.flush();
bw.close();
log.info("Written data into the file");
} else {
createFileIfNoExists();
}

} catch (IOException e) {
log.error("Failed to write content " + e.getMessage());

}
}

private static void createFileIfNoExists() {
File fileCreate = new File(fileName);
try {
if (fileCreate.exists()) {
boolean isFileExecutable = fileCreate.canRead()
&& fileCreate.canWrite();
if (isFileExecutable) {
log.info("File Exist and you can write in file "
+ fileCreate.getAbsolutePath());
}
} else {
fileCreate.createNewFile();
// fileCreate.setWritable(false);
log.info("File Creation Completed, Absolute path name "
+ fileCreate.getAbsolutePath());
}

} catch (IOException e) {
log.error("File Creation Operation Failed : " + e.getMessage());
}
}

}

No comments :

// Below script tag for SyntaxHighLighter