码迷,mamicode.com
首页 > 编程语言 > 详细

java读取文件

时间:2014-12-01 15:56:46      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   color   os   sp   java   for   文件   

以字节的方式读取:

            InputStream inputStream = new FileInputStream(file);
            int temp = -1;
            StringBuilder sb = new StringBuilder();
            while((temp = inputStream.read()) != -1){
                sb.append((char)temp);
            }
            inputStream.close();

也可以多个字节一起读取:

            InputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[10];
            StringBuilder sb = new StringBuilder();
            int length = -1;
            while((length = inputStream.read(bytes))!= -1){
                sb.append(new String(bytes,0,length,Charset.forName("utf-8")));
            }
            inputStream.close();

以字符的方式读取:

            InputStream inputStream = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(inputStream,Charset.forName("utf-8"));
            StringBuilder sb = new StringBuilder();
            int temp = -1;
            while((temp = (isr.read()))!= -1){
                sb.append((char)temp);
            }
            inputStream.close();
            isr.close();

或者用封装的BufferedReader按行读取,效率更高:

InputStream inputStream = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(inputStream,Charset.forName("utf-8"));
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = bufferedReader.readLine())!=null){
                sb.append(line + ‘\n‘);
            }
            inputStream.close();
            isr.close();
            bufferedReader.close();

 

java读取文件

标签:style   blog   ar   color   os   sp   java   for   文件   

原文地址:http://www.cnblogs.com/hithlb/p/4135108.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!