get String From File - Java File Path IO

Java examples for File Path IO:Text File

Description

get String From File

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main {


    public static String getStringFromFile(String filePath)
            throws Exception {
        FileInputStream fin = new FileInputStream(new File(filePath));
        String ret = convertStreamToString(fin);
        fin.close();/*w w  w. ja va2  s.  c o m*/
        return ret;
    }

    public static String convertStreamToString(InputStream is)
            throws Exception {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        reader.close();
        return sb.toString();
    }
}

Related Tutorials