Code Robo
Formatter
Comparator
Tester
Merger
Converter
Utility
Java Code Complience
Validator
EncoderDecoder
Virtual Service
Java File Utility Functions
       Talk to EasyAssistant

Java File Utility Functions. It provides sample java File functions. Copuple of examples are shown for Java File operation function which can be copied from here and used in any java project. Its shows both the read and write operation . Sample code uses java.io and java.util package. Does not uses any third party library class to process file.


Java Utility Code Content:
package sg.ardpfnd.util;

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.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;

public class FileUtility {
	public static final String TOOL_FOLDER_NAME = "coderobo/";

	public static void writeToFile(String fileNameWithPath, String content) {

		File file = null;
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {

			file = new File(fileNameWithPath);
			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
			fw = new FileWriter(file.getAbsoluteFile());
			bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (Exception e) {

			}
			try {

				fw.close();

			} catch (Exception e) {

			}
		}
	}

	public static Properties readPropertiesFromFile(String fileNameWithPath) {

		BufferedReader br = null;
		FileReader fr = null;
		String sCurrentLine = "";
		Properties prop = new Properties();
		try {

			fr = new FileReader(fileNameWithPath);
			br = new BufferedReader(fr);
			sCurrentLine = br.readLine();
			while (sCurrentLine != null) {

				addToProperties(sCurrentLine, prop);
				sCurrentLine = br.readLine();

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (Exception e) {

			}
			try {
				fr.close();
			} catch (Exception e) {
			}
		}
		return prop;
	}

	private static void addToProperties(String str, Properties prop) {
		if (str == null)
			return;
		if (str.startsWith("#"))
			return;

		StringTokenizer st = new StringTokenizer(str, "=");

		if (st.countTokens() != 2)
			return;

		String keyStr = st.nextToken();
		String valueStr = st.nextToken();
		if (keyStr == null)
			keyStr = "";
		if (keyStr == valueStr)
			valueStr = "";

		prop.put(keyStr.trim(), valueStr.trim());

		return;

	}

	public static String readFromFile(String fileNameWithPath, String newLine) {

		Set<String> lineList = new HashSet<String> ();

		BufferedReader br = null;
		FileReader fr = null;
		String sCurrentLine = "";
		String fContent = "";

		try {

			fr = new FileReader(fileNameWithPath);

			br = new BufferedReader(fr);
			sCurrentLine = br.readLine();

			while (sCurrentLine != null) {
				fContent = fContent + sCurrentLine + newLine;
				sCurrentLine = br.readLine();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {

				br.close();

			} catch (Exception e) {

			}
			try {

				fr.close();

			} catch (Exception e) {

			}
		}

		return fContent;
	}

	public static String readFileAndReturnEntireContent(String fileNameWithPath) {
		Set<String> lineList = new HashSet<String> ();

		BufferedReader br = null;
		FileReader fr = null;
		String sCurrentLine = "";
		String fContent = "";

		try {
			fr = new FileReader(fileNameWithPath);
			br = new BufferedReader(fr);
			sCurrentLine = br.readLine();
			while (sCurrentLine != null) {
				fContent = fContent + sCurrentLine + "\n";
				sCurrentLine = br.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (Exception e) {
			}
			try {
				fr.close();
			} catch (Exception e) {
			}
		}

		return fContent;
	}

	public static Set<String> readAndReturnAsListOfString(String fileNameWithPath) {

		Set<String> lineList = new HashSet<String> ();

		BufferedReader br = null;
		FileReader fr = null;
		String sCurrentLine = "";
		String fContent = "";

		try {

			try {
				fr = new FileReader(fileNameWithPath);

			} catch (FileNotFoundException ex) {
				ex.printStackTrace();
			}

			br = new BufferedReader(fr);
			sCurrentLine = br.readLine();

			while (sCurrentLine != null) {

				sCurrentLine = sCurrentLine.trim();
				fContent = fContent + sCurrentLine;
				lineList.add(sCurrentLine);
				sCurrentLine = br.readLine();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (Exception e) {

			}
			try {
				fr.close();
			} catch (Exception e) {
			}
		}

		return lineList;
	}

	
	public static List executeABatchFile(String shOrBatFileNameWithPath, String logFileFolderPath) throws Exception {
		boolean flag = true;

		Runtime runtime = Runtime.getRuntime();

		List logFileList = new ArrayList();

		try {

			ProcessBuilder processBuilder = new ProcessBuilder(shOrBatFileNameWithPath, logFileFolderPath);
			Process process = processBuilder.start();
			BufferedReader readerPo = new BufferedReader(new InputStreamReader(process.getInputStream()));

			flag = true;

			String line = "";

			long lineCount = 0;

			while (flag) {
				line = readerPo.readLine();
				if (line == null) {
					flag = false;

				} else {
					logFileList.add(line);
				}
			}

			int waitFor = process.waitFor();

			if (waitFor == 0) {
				return logFileList;
			}
			System.out.println("could not give permission to ___+" + waitFor);
			BufferedReader readerErrorPo = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			flag = true;

			while (flag) {
				String error = readerErrorPo.readLine();
				if ((error == null) || (error.contains("null"))) {
					flag = false;
					break;
				} else {

					System.out.println("-----error in givign permission$$*-----" + error);
				}
			}

		} catch (Exception e) {

			e.printStackTrace();
			throw e;
		}

		return logFileList;

	}

	public static String getEncoding(String str) {

		if (str == null)
			return "";
		// <?xml version="1.0" encoding="iso-8859-1" ?>

		str = str.trim();
		int indexOfEndQuestionMark = -1;
		int indexOfEncoding = -1;
		String encodingValue = "";
		int indexOfEqualAfterEncoding = -1;
		if (str.startsWith("<?xml")) {
			indexOfEndQuestionMark = str.indexOf("?>");
			if (indexOfEndQuestionMark <= 0)
				indexOfEndQuestionMark = str.indexOf("? >");

			if (indexOfEndQuestionMark > 0) {
				System.out.println("encodingValue=" + encodingValue);
				indexOfEncoding = str.indexOf("encoding");
				System.out.println("indexOfEncoding=" + indexOfEncoding);

				if (indexOfEncoding > 0) {
					indexOfEqualAfterEncoding = str.indexOf('=', indexOfEncoding);
					if (indexOfEqualAfterEncoding > 0) {
						if (indexOfEndQuestionMark > indexOfEqualAfterEncoding) {
							encodingValue = str.substring(indexOfEqualAfterEncoding + 1, indexOfEndQuestionMark);
							encodingValue = encodingValue.replace('=', ' ');
							encodingValue = encodingValue.replace('?', ' ');
							encodingValue = encodingValue.trim();

							System.out.println("encodingValue=" + encodingValue);
						}
					}
				}
			}

		}

		System.out.println("RetutnencodingValue=" + encodingValue);

		return encodingValue.trim();

	}

	public static void writeXMLToFileWithEncoding(String fileNameWithPath, String str) throws Exception {

		System.out.println("fileNameWithPath=" + fileNameWithPath);
		String encoding = getEncoding(str);
		System.out.println("encodingValueGot=" + encoding);

		if (encoding.isEmpty()) {
			System.out.println("encoding is empty. USING UTF-8 encoding");
			encoding = "UTF-8";
			str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> " + str;

		}

		File file = null;
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {

			String content = str;

			file = new File(fileNameWithPath);

			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
			fw = new FileWriter(file.getAbsoluteFile());

			bw = new BufferedWriter(fw);
			System.out.println(encoding);
			String strToWrite = "";
			System.out.println("encoding=" + encoding);
			encoding = encoding.replace('"', ' ');
			encoding = encoding.replace('"', ' ');
			encoding = encoding.replace('"', ' ');
			encoding = encoding.replace('"', ' ');
			encoding = encoding.trim();

			if ("UTF-8".equalsIgnoreCase(encoding)) {
				strToWrite = new String(str.getBytes(StandardCharsets.UTF_8));
			} else if ("UTF-16".equalsIgnoreCase(encoding)) {
				strToWrite = new String(str.getBytes(StandardCharsets.UTF_16));
			} else if (encoding.toLowerCase().startsWith("iso")) {
				strToWrite = new String(str.getBytes(StandardCharsets.ISO_8859_1));
			} else if (encoding.toLowerCase().contains("asc")) {
				strToWrite = new String(str.getBytes(StandardCharsets.US_ASCII));
			} else {
				strToWrite = new String(str.getBytes(encoding));
			}

			bw.write(strToWrite);
			bw.close();

			System.out.println("Written to file. with encoding " + encoding);

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("" + e);
			throw e;
		} finally {
			try {

				bw.close();

			} catch (Exception e) {

			}
			try {

				fw.close();

			} catch (Exception e) {

			}
		}
	}

	public static void writeToFileWithUTFEncoding(String fileNameWithPath, String str, String encodingCharSet)
			throws Exception {

		File file = null;
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			file = new File(fileNameWithPath);
			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			fw = new FileWriter(file.getAbsoluteFile());

			bw = new BufferedWriter(fw);

			bw.write(new String(str.getBytes(StandardCharsets.UTF_8)));
			bw.close();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (Exception e) {

			}
			try {
				fw.close();
			} catch (Exception e) {

			}
		}

	}

}










Please provide your feedback here
It has been explained in this video (https://youtu.be/bxkNb0GuELY). Please watch it.
 



Post Your Comment:
Name :
Email ( Optional) :
Comments / Suggestion (* Required) It is required: :
: