Java InputStreamReader Read readFileAsJson(String path)

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

Description

Read json message from file.

License

Apache License

Parameter

Parameter Description
path String

Return

String json message.

Declaration

public static String readFileAsJson(String path) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    /**/*from  ww w . j a v a 2 s.  co m*/
     * Read json message from file.
     * 
     * NOTE: This method is not prefered to read large size files, it would cause out of memory exception.
     * 
     * @param path String
     * @return String json message.
     */
    public static String readFileAsJson(String path) {

        return readFileAsJson(new File(path));

    }

    public static String readFileAsJson(File jsonFile) {

        if (!jsonFile.exists())
            throw new RuntimeException(jsonFile.getAbsolutePath()
                    + " does not exist!");

        StringBuilder json = new StringBuilder();
        BufferedReader fileReader = null;

        try {
            fileReader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(jsonFile), "UTF-8"));

            String line = null;
            while ((line = fileReader.readLine()) != null) {
                json.append(line);
            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

            try {
                if (null != fileReader)
                    fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return json.toString();
    }
}

Related

  1. readFile(String path, String charset)
  2. readFile(ZipInputStream zin)
  3. readFileAddLine(String filePath, Object object)
  4. readFileAll(File file, String charsetName)
  5. readFileAsArray(String path)
  6. readFileAsList(String path)
  7. readFileByCharAsString(String path, String encode)
  8. readFileCharacters(File file, boolean fix)
  9. readFileData(File file)