Functions/Methods to
* create a file
* delete a file
* write to a file
* extract lines from a file into an array
* read from a file
**** Usage ****
import java.io.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class FileUtils {
public static void main(String[] args){
}
//* Utility Function to Search a file for a string at a specified location in the line. Write this line to a new file.
static public void ExtractLinestoFile(String sIFile, int iLocation, String sExpectedString, String sOFile ) {
File iFile = new File(sIFile);
File oFile = new File(sOFile);
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(iFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
String sub = line.substring(iLocation,iLocation+sExpectedString.length());
if (sub.equals(sExpectedString)) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
sIFile = null;
String sContents;
sContents = contents.toString();
//sContents = sContents.trim();
Writer output;
System.out.println("Writing to file " + sOFile);
try {
output= new BufferedWriter(new FileWriter(oFile));
//System.out.println(sContents);
//FileWriter always assumes default encoding is OK!
output.write(sContents);
output.close();
}
catch (IOException ex){
ex.printStackTrace();
}
}
//* Utility Function to Search a file for a string at a specified location in the line. Write this line to a new file.
static public String ExtractLinestoString(String sIFile, int iRowLocation, int iColLocation, int iNumberOfChars ) {
String sExtractedString = "";
File iFile = new File(sIFile);
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(iFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
int i = 1;
while (( line = input.readLine()) != null){
if(iRowLocation == i){
sExtractedString = line.substring(iColLocation,iColLocation+iNumberOfChars);
break;
}
i = i + 1;
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
sIFile = null;
return sExtractedString;
}
//* Utility Function to Search a file for a string at a specified location in the line. Returns 1 if the string is found else 0
static public int SearchFileContents(String sFile, String sExpectedString, int iLocation) {
File aFile = new File(sFile);
int ifound = 0;
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
String newline = null;
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
newline = line;
String sub = newline.substring(iLocation,iLocation+sExpectedString.length());
if (sub.equals(sExpectedString)) {
//System.out.println("Match found");
ifound = 1;
}
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
aFile = null;
if (ifound==1){
return 1;
}
else
{
return 0;
}
}
//* Utility Function to Search a file for a string at any location in the line. Returns 1 if the string is found else 0
static public int SearchFile(String sFile, String sExpectedString) {
File aFile = new File(sFile);
int ifound = 0;
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
String newline = null;
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
if (line.indexOf(sExpectedString) >= 0) {
//System.out.println("Match found");
ifound = 1;
}
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
aFile = null;
if (ifound==1){
return 1;
}
else
{
return 0;
}
}
//* Utility function ot delete a file specified by the absolute path of the file
public static int Delete(String sFiletoDelete) {
// A File object to represent the filename
File f = new File(sFiletoDelete);
// Make sure the file or directory exists and isn't write protected
if (!f.exists())
throw new IllegalArgumentException(
"Delete: no such file or directory: " + sFiletoDelete);
if (!f.canWrite())
throw new IllegalArgumentException("Delete: write protected: "
+ sFiletoDelete);
// If it is a directory, make sure it is empty
if (f.isDirectory()) {
String[] files = f.list();
if (files.length > 0)
throw new IllegalArgumentException(
"Delete: directory not empty: " + sFiletoDelete);
}
// Attempt to delete it
boolean success = f.delete();
if (!success){
throw new IllegalArgumentException("Delete: deletion failed");
}
else
{
return 1;
}
}
//* Utility function to delete file from a directory specified by the absolute path
public static int Deletefiles(String sDirectory){
// A File object to represent the Directory
File f = new File(sDirectory);
String[] files = f.list();
if (files.length > 0){
for (int i=0; i<files.length; i++) {
File fx = new File(sDirectory + files[i]);
System.out.println(sDirectory + files[i]);
// Attempt to delete it
boolean success = fx.delete();
System.out.println("Deletion Successful " + success);
fx = null;
}
return 0;
}
else
{
return 1;
}
}
//* Utility function to rename a file (specify the absolute paths for both the old and new file)
public static void Rename(String sOldfile, String sNewfile) throws IOException {
File f = new File(sOldfile);
f.renameTo(new File(sNewfile));
}
//* Utility function to replace a part of all the lines in a file with the specified string and output to another file
static public void ReplaceContents(String sIFile, String sOFile,int iStart, int iNumber, String sReplacement) {
/**
sIFile - Input file
sOFile - Output file created by updating the input file
iStart - the starting position where the replacement has to occur
iNumber - the number of characters past the starting index to replace
sReplacement - the string that will substitute the original contents
**/
File iFile = new File(sIFile);
File oFile = new File(sOFile);
StringBuilder contents = new StringBuilder();
System.out.println("Reading from file " + sIFile);
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(iFile));
try {
String line = null; //not declared within while loop
String newline = null;
while (( line = input.readLine()) != null){
//newline = line.replaceAll(line.substring(0,iStart+iNumber), line.substring(0,iStart)+sReplacement);
newline = line.replace(line.substring(0,iStart+iNumber), line.substring(0,iStart)+sReplacement);
contents.append(newline);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
String sContents;
sContents = contents.toString();
//sContents = sContents.trim();
Writer output;
System.out.println("Writing to file " + sOFile);
try {
output= new BufferedWriter(new FileWriter(oFile));
//System.out.println(sContents);
//FileWriter always assumes default encoding is OK!
output.write(sContents);
output.close();
}
catch (IOException ex){
ex.printStackTrace();
}
}
//* Utility function to replace a part of all the lines in a file with the specified string and output to another file
static public StringBuilder ReplaceContentsReturnString(String sIFile,int iStart, int iNumber, String sReplacement) {
/**
sIFile - Input file
iStart - the starting position where the replacement has to occur
iNumber - the number of characters past the starting index to replace
sReplacement - the string that will substitute the original contents
**/
File iFile = new File(sIFile);
StringBuilder contents = new StringBuilder();
System.out.println("Reading from file " + sIFile);
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(iFile));
try {
String line = null; //not declared within while loop
String newline = null;
while (( line = input.readLine()) != null){
//newline = line.replaceAll(line.substring(0,iStart+iNumber), line.substring(0,iStart)+sReplacement);
newline = line.replace(line.substring(0,iStart+iNumber), line.substring(0,iStart)+sReplacement);
contents.append(newline);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents;
}
//* Utility function to create a file specified by the absolute path
public static void CreateFile(String arg) throws IOException{
try {
File f = new File(arg);
// Create file if it does not exist
boolean success = f.createNewFile();
if (success) {
// File did not exist and was created
System.out.println("New file " + arg + " has been created to the current directory");
} else {
// File already exists
System.out.println("New file " + arg + " already exists in the current directory");
}
} catch (IOException e) {
}
}
//* Utility function to create a folder specified by the absolute path
public static void CreateFolder(String arg) throws IOException{
File f = new File(arg);
// Create folder if it does not exist
boolean success = f.mkdir();
if (success) {
// Folder did not exist and was created
System.out.println("New folder " + arg + " has been created to the current directory");
} else {
// File already exists
System.out.println("New folder " + arg + " already exists in the current directory");
}
}
//* Utility function to read the contents of a file (specified by the absolute path) into an array
static public String[] ReadFileArray(String sFile) {
File aFile = new File(sFile);
ArrayList<String> arr = new ArrayList<String>();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
int i=0;
while (( line = input.readLine()) != null){
arr.add(line);
i++;
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
String aData[] = (String[]) arr.toArray ( new String[arr.size()]);
return aData;
}
//* Utility function to perform a line by line comparison of two files. The lines do not have to be in the same order in the two files for the comparison to pass.
public static String[] CompareContents(String sExpectedfile, String sActualfile) {
String[] aExpectedContents=ReadFileArray(sExpectedfile);
String[] aActualContents=ReadFileArray(sActualfile);
ArrayList<String> results = new ArrayList<String>();
int ilinefound = 0;
results.add("Comparing Files " + sExpectedfile + " and " + sActualfile);
if (aExpectedContents.length == 0){
results.add("WARNING,The Expected file has no contents to compare against");
}
if (aExpectedContents.length != aActualContents.length){
results.add("FAIL,The lengths of the two file do not match , expected - " + aExpectedContents.length + " and actual - " + aActualContents.length);
}
for (int j = 0; j < aExpectedContents.length; j++) {
ilinefound = 0;
for (int i = 0; i < aActualContents.length; i++) {
if(aExpectedContents[j].equals(aActualContents[i])){
ilinefound = 1;
break;
}
}
if (ilinefound == 0){
results.add("FAIL,The expected line - " + aExpectedContents[j] + " - not found in actual file");
}
else
{
results.add("PASS,The expected line - " + aExpectedContents[j] + " - found in actual file");
}
}
String aResults[] = (String[]) results.toArray ( new String[results.size()]);
return aResults;
}
//* Utility function to append a line/lines to a file (specified by the absolute path).
public static void AppendFile(String arg, String... args){
try {
FileWriter out = new FileWriter(arg,true);
BufferedWriter writer = new BufferedWriter(out);
for (String line : args ){
writer.write(line);
writer.newLine();
//System.out.println (line);
}
writer.close();
} catch (IOException e) {
}
}
}