Java File Read via ByteBuffer readJsonFromFile(String path)

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

Description

Reads JSON object (in string format) from specified file.

License

Open Source License

Parameter

Parameter Description
path file path to read

Exception

Parameter Description
IOException an exception
JSONException an exception

Return

JSONObject read from specified file

Declaration

public static JSONObject readJsonFromFile(String path) throws IOException, JSONException 

Method Source Code

//package com.java2s;
/**/*from   w  w  w.j a va  2s.c o m*/
 * Copyright 2016 LinkedIn Corp. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class Main {
    /**
     * Reads JSON object (in string format) from specified file.
     *
     * @param path file path to read
     * @return JSONObject read from specified file
     * @throws IOException
     * @throws JSONException
     */
    public static JSONObject readJsonFromFile(String path) throws IOException, JSONException {
        return new JSONObject(readStringFromFile(path));
    }

    /**
     * Reads entire contents of specified file as a string.
     *
     * @param path file path to read
     * @return string read from specified file
     * @throws IOException
     */
    public static String readStringFromFile(String path) throws IOException {
        File file = new File(path);
        byte[] encoded = new byte[(int) file.length()];
        DataInputStream ds = null;
        try {
            ds = new DataInputStream(new FileInputStream(file));
            ds.readFully(encoded);
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
        return Charset.defaultCharset().decode(ByteBuffer.wrap(encoded)).toString();
    }
}

Related

  1. readInt(ReadableByteChannel channel)
  2. readInt16(DataInput di)
  3. readIntArray(DataInput input)
  4. readIntLittleEndian(InputStream in)
  5. readIntoBuffer(RandomAccessFile file, int offset, int size)
  6. readLargeFile(File file)
  7. readLong(byte[] src, int pointer)
  8. readLong(InputStream input)
  9. readLong(InputStream is)