Java Path File Read nio readFromFile(String path)

Here you can find the source of readFromFile(String path)

Description

read From File

License

Open Source License

Parameter

Parameter Description
path a parameter

Return

Since it is used in GWT context Java.nio can not be used and guava comes in the wrong flavor

Declaration

public static String readFromFile(String path) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**/*from www . j ava2s.c o m*/
     * 
     * @param path
     * @return
     * 
     *       Since it is used in GWT context Java.nio can not be used and
     *         guava comes in the wrong flavor
     * 
     */
    public static String readFromFile(String path) {
        File file = new File(path);

        if (!file.exists())
            return "";

        if (file.isDirectory())
            throwRuntimeException("file expected, this is a directory: " + path);

        try {
            FileInputStream fin = new FileInputStream(file);
            return readFromStream(fin);
        } catch (IOException e) {
            throwRuntimeException(e.getMessage());
        }

        return "";
    }

    private static void throwRuntimeException(String msg) {
        throw new RuntimeException(msg);
    }

    public static String readFromStream(InputStream input) {
        StringBuilder sb = new StringBuilder();

        BufferedInputStream bin = null;
        try {
            bin = new BufferedInputStream(input);
            byte[] contents = new byte[1024];

            int bytesRead = 0;
            String strFileContents;

            while ((bytesRead = bin.read(contents)) != -1) {

                strFileContents = new String(contents, 0, bytesRead);
                sb.append(strFileContents);
            }

        } catch (IOException e) {
            throwRuntimeException(e.getMessage());
        } finally {
            try {
                if (bin != null)
                    bin.close();
            } catch (IOException ioe) {
            }
        }
        return sb.toString();

    }
}

Related

  1. readFileLines(Path file)
  2. readFileRows(Path path)
  3. readFileToSingleString(String path)
  4. readFileToString(@Nonnull Path file)
  5. readFromFile(Path absolutePath)
  6. readFromFile(String path)
  7. readFully(Path filePath)
  8. readIntsFromFile(String filePath)
  9. readJson(Class dataClass, Path path)