How to write a Java Program to Java Read / Write Text file ?
Solution:
private String readTextFile(String filePath) { StringBuilder str = new StringBuilder(""); try { FileInputStream fips = new FileInputStream(filePath); InputStreamReader ipsReader = new InputStreamReader(fips, "UTF-8"); int character; while ((character = ipsReader.read()) != 1) { str.append((char) character); } ipsReader.close(); } catch (FileNotFoundException ex) { // may happen during file IO mapping System.out.println(ex.getCause().getMessage()); } catch (UnsupportedEncodingException ex) { // may happen during load unsupported charset file System.out.println(ex.getCause().getMessage()); } catch (IOException ex) { // may happen during read file System.out.println(ex.getCause().getMessage()); } return str.toString(); } private void writeTextFile(String filePath, String content) { try { FileOutputStream fops = new FileOutputStream(filePath); OutputStreamWriter opsWriter = new OutputStreamWriter(fops, "UTF-8"); opsWriter.write(content); opsWriter.close(); } catch (FileNotFoundException ex) { // may happen during file IO mapping System.out.println(ex.getCause().getMessage()); } catch (UnsupportedEncodingException ex) { // may happen during load unsupported charset file System.out.println(ex.getCause().getMessage()); } catch (IOException ex) { // may happen during read file System.out.println(ex.getCause().getMessage()); } }