Android Text File Read readFile(File file)

Here you can find the source of readFile(File file)

Description

Reads file and returns contents as string

Parameter

Parameter Description
file java.io.File object of file to read

Exception

Parameter Description
FileNotFoundException thrown if file specified does not exist

Return

file contents as String, or "" if file is blank

Declaration

public static String readFile(File file) throws FileNotFoundException 

Method Source Code

//package com.java2s;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    /**//  ww  w .ja v a2  s  .  c o  m
     * Reads file and returns contents as string
     * @param file java.io.File object of file to read
     * @return file contents as String, or "" if file is blank
     * @throws FileNotFoundException thrown if file specified does not exist
     */
    public static String readFile(File file) throws FileNotFoundException {

        //setup
        String filePath = file.getAbsolutePath();
        FileInputStream fstream = new FileInputStream(filePath);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        String forReturn = "";

        try {

            // Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                //add to returned String
                forReturn += strLine;
            }

            // Close the input stream
            in.close();

        } catch (IOException e) {
            //do nothing, file is presumably empty so return ""
        }

        return forReturn;

    }
}

Related

  1. read(String fileName)
  2. read(String pathName)
  3. readCipherSuites(String file)
  4. readClasspathTextFile(String filename)
  5. readFile(File file)
  6. readFile(File file)
  7. readFile(File file, String encoding)
  8. readFile(File in)
  9. readFile(String fileName)