Java读取.json文件

本文介绍了一种Android客户端实现远程版本更新的方法。通过在服务器上放置一个.json文件存储最新的版本信息,客户端通过网络请求该文件并比对本地版本,从而决定是否提示用户进行更新。

最近用到了Android客户端需要根据存放在服务器的apk更新版本的问题,对于这个问题我的思路是,在服务器创建一个.json文件,里面按照json格式拼接好字符串,然后客户端远程请求服务器的.json文件,获取设置好的版本号跟当前用户使用的版本号对比.
文件位置
文件内容
一,读取本地的.json

public static String ReadFile(String path){
        String laststr="";
        File file=new File(path);
        BufferedReader reader=null;
        try{
        reader=new BufferedReader(new FileReader(file));
        String tempString=null;
        //int line=1;
        while((tempString=reader.readLine())!=null){
        //System.out.println("line"+line+":"+tempString);
        laststr=laststr+tempString;
        //line++;
        }
        reader.close();
        }catch(IOException e){
        e.printStackTrace();
        }finally{
        if(reader!=null){
        try{
        reader.close();
        }catch(IOException el){
        }  }  }
        return laststr;
        }

二,读取网络上的.json

 public static void main(String[] args) {
         //查询Ip信息的接口,返回json
        String url="http://XX.XX.XX.XX:8088/XXXX/date/update.json";
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        //得到的json数据
        System.out.println(result);
    }

复制代码可以直接使用

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值