read String From File - Java java.io

Java examples for java.io:BufferedReader

Description

read String From File

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] argv) {
        File file = new File("Main.java");
        System.out.println(readStringFromFile(file));
    }//from  w w w . ja  va 2  s  . co  m

    public static String readStringFromFile(File file) {
        String rtStr = "";
        BufferedReader in;
        try {
            in = new BufferedReader(new FileReader(file));
            String tempStr = "";
            while ((tempStr = in.readLine()) != null) {
                rtStr += tempStr + "\n";
            }
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return rtStr;
    }
}

Related Tutorials