Java BufferedReader Read readFile(File in)

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

Description

Reads a file and converts it to a String via a byte array and inputStream.available() I'm not positive that inputStream.available() works the same under multi-threading

License

Open Source License

Parameter

Parameter Description
in - File object to read - should be character data

Return

String a string version of the data

Declaration

public static String readFile(File in) throws IOException 

Method Source Code


//package com.java2s;
import java.io.*;

public class Main {
    /**/* w w  w . j a  v  a2s.com*/
     * Reads a file and converts it to a String via a byte array and inputStream.available()
     * I'm not positive that inputStream.available() works the same under multi-threading
     * @param in - File object to read - should be character data
     * @return String a string version of the data
     */
    public static String readFile(File in) throws IOException {
        /*
        InputStream inputStream = new FileInputStream(in);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        inputStream.close();
        return new String(bytes);
         */

        //Richard's implementation, this may be more thread safe than using inputStream.available()
        String line = null;
        StringBuffer content = new StringBuffer("");
        //if (debug) System.out.println("Reading " + in);
        try {
            BufferedReader bReader = new BufferedReader(new FileReader(in));
            while ((line = bReader.readLine()) != null)
                content.append(line + "\n");
            bReader.close();
        } catch (IOException ioe) {
            System.err.println("Error reading " + in + ": " + ioe);
        }
        return content.toString();
    }
}

Related

  1. readFile(File file)
  2. readFile(File file, boolean useSystemLineSeparator)
  3. readFile(File file, int header)
  4. readFile(File filename)
  5. readFile(File from)
  6. readFile(File inputFile)
  7. readFile(File location)
  8. readFile(File path)
  9. readFile(File testPage)