标签: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();
标签:style blog ar color os sp java for 文件
原文地址:http://www.cnblogs.com/hithlb/p/4135108.html