Here you can find the source of fileToString(File file, String charsetName)
Parameter | Description |
---|---|
file | the file to be transformed |
charsetName | encoding of the file |
public static String fileToString(File file, String charsetName)
//package com.java2s; //License from project: Apache License import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; public class Main { /**/*from w w w . j ava 2s. co m*/ * Transforms a file into a string. * * @param file * the file to be transformed * @param charsetName * encoding of the file * @return the string containing the content of the file */ public static String fileToString(File file, String charsetName) { FileInputStream fileInputStream = null; try { try { fileInputStream = new FileInputStream(file); return streamToString(fileInputStream, charsetName); } finally { if (fileInputStream != null) { fileInputStream.close(); } } } catch (Exception e) { throw new RuntimeException(e); } } /** * Transforms a file into a string. * * @param fileName * name of the file to be transformed * @param charsetName * encoding of the file * @return the string containing the content of the file */ public static String fileToString(String fileName, String charsetName) { return fileToString(new File(fileName), charsetName); } /** * Transforms a stream into a string. * * @param is * the stream to be transformed * @param charsetName * encoding of the file * @return the string containing the content of the stream */ public static String streamToString(InputStream is, String charsetName) { try { Reader r = null; try { r = new BufferedReader(new InputStreamReader(is, charsetName)); return readerToString(r); } finally { if (r != null) { try { r.close(); } catch (IOException e) { } } } } catch (Exception e) { throw new RuntimeException(e); } } /** * Transforms a reader into a string. * * @param reader * the reader to be transformed * @return the string containing the content of the reader */ public static String readerToString(Reader reader) { try { StringBuilder sb = new StringBuilder(); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { sb.append(buf, 0, numRead); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } } }