Here you can find the source of readJsonFromFile(String path)
Parameter | Description |
---|---|
path | file path to read |
Parameter | Description |
---|---|
IOException | an exception |
JSONException | an exception |
public static JSONObject readJsonFromFile(String path) throws IOException, JSONException
//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(); } }