您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页Java一次性读取文本文件所有内容

Java一次性读取文本文件所有内容

来源:二三娱乐

刚开始学习Java,最近需要将一个json文件的内容都读取到String对象中,然后进行处理。

示例代码:

//读取json文件的内容 
       public static String readToString(String fileName) {  
            String encoding = "UTF-8";  
            File file = new File(fileName);  
            Long filelength = file.length();  
            byte[] filecontent = new byte[filelength.intValue()];  
            try {  
                FileInputStream in = new FileInputStream(file);  
                in.read(filecontent);  
                in.close();  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            try {  
                return new String(filecontent, encoding);  
            } catch (UnsupportedEncodingException e) {  
                System.err.println("The OS does not support " + encoding);  
                e.printStackTrace();  
                return null;  
            }  
        }

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务