Java - Write code to read File As String

Requirements

Write code to read File As String

Pass in the file path as a string

Hint

Create InputStream via FileInputStream

Demo

//package com.book2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    public static void main(String[] argv) {
        String filePath = "book2s.com";
        System.out.println(readFileAsString(filePath));
    }//ww  w. ja  va2s  .c  o  m

    public static String readFileAsString(String filePath) {
        byte[] b = null;

        try {

            File file = new File(filePath);

            InputStream in;
            in = new FileInputStream(file);

            b = new byte[(int) file.length()];
            int len = b.length;
            int total = 0;

            while (total < len) {
                int result = in.read(b, total, len - total);

                if (result == -1) {
                    break;
                }
                total += result;
            }

            in.close();

        } catch (FileNotFoundException e) {
            return null;
        } catch (IOException e) {
            return null;
        }

        return new String(b /*, "UTF8" */);
    }
}