好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java的url方式、本地方式获取json文件内容

因为工作原因需要读取 json 文件,最先是使用url方式不符合要求pass。又使用本地方式读取。记录一下方便后期查看。
注:因为资料都是从网上摘抄,如有问题请告知我。

1.url方式

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

/**

    * 通过网络访问json并读取文件

    * @param url:http://127.0.0.1:80/dashboard/dept_uuid.json

    * @return:json文件的内容

    */

   public static string loadjson (string url) {

     stringbuilder json = new stringbuilder();

     try {

       url urlobject = new url(url);

       urlconnection uc = urlobject.openconnection();

       bufferedreader in = new bufferedreader( new inputstreamreader(uc.getinputstream(), "utf-8" ));

       string inputline = null ;

       while ( (inputline = in.readline()) != null ) {

         json.append(inputline);

       }

       in.close();

     } catch (malformedurlexception e) {

       e.printstacktrace();

     } catch (ioexception e) {

       e.printstacktrace();

     }

     return json.tostring();

   }

2.本地文件读取

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

/**

    * 通过本地文件访问json并读取

    * @param path:e:/svn/05.hospital/templatedept_uuid.json

    * @return:json文件的内容

    */

   public static string readfile(string path){

     string laststr= "" ;

     file file= new file(path); // 打开文件

     bufferedreader reader= null ;

     try {

       fileinputstream in = new fileinputstream(file);

       reader= new bufferedreader( new inputstreamreader(in, "utf-8" )); // 读取文件

       string tempstring= null ;

       while ((tempstring=reader.readline())!= null ){

         laststr=laststr+tempstring;

       }

       reader.close();

     } catch (ioexception e){

       e.printstacktrace();

     } finally {

       if (reader!= null ){

         try {

           reader.close();

         } catch (ioexception el){

         }

       }

     }

     return laststr;

   }

原文链接:https://blog.csdn.net/haizhihen123/article/details/54912636

查看更多关于java的url方式、本地方式获取json文件内容的详细内容...

  阅读:38次