Java examples for File Path IO:Text File
read file To String
//package com.java2s; import java.io.*; import java.nio.charset.Charset; public class Main { public static void main(String[] argv) throws Exception { String fileName = "java2s.com"; System.out.println(fileToString(fileName)); }//from w w w . ja va 2 s. c o m public static String fileToString(String fileName) { File file = new File(fileName); InputStream in = null; try { in = new FileInputStream(file); } catch (FileNotFoundException fnfe) { System.out.println("File not found: " + fileName); } byte[] b = new byte[(int) file.length()]; int len = b.length; int total = 0; int result = 0; while (total < len) { try { result = in.read(b, total, len - total); } catch (IOException ioe) { System.out.println("Unable to read from file"); } if (result == -1) { break; } total += result; } return new String(b, Charset.forName("UTF-8")); } }