package com.winston.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class InputStreamTest {
public static void main (String[] args) {
test2();
}
private static void test2 () {
try {
InputStream is = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\test.txt"));
//缓冲区
byte[] b = new byte[4];
//本次读取长度
int len;
StringBuffer sbf = new StringBuffer();
while((len=is.read(b))!=-1){//把读取的数据放到i中
for (byte c : b) {
System.out.print(c+" ");
}
System.out.println();
String tmp = new String(b,0,len,"UTF-8");
System.out.println("本次读取长度:"+len+"、内容:"+tmp);
sbf.append(tmp);
}
System.out.println("-------读取完成------");
System.out.println(sbf.toString());
//把字节数组转成字符串
//关闭流
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
本例设置的byte数组长度为4。每次读取4个字节。
文档采用UTF-8编码格式。其中字母各占一个字节。汉字占3个或4个字节。
读取字节流的时候 第一次读取sss三个字节。UTF-8编码的“大”占了3个字节。因此会读取sss加上“大”的第一个字节。所以字节流读取中文的时候 会存在乱码的情况。
public class BufferedReader extends Reader
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
使用字符流读取文件。
package com.winston.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
public class InputStreamTest {
public static void main (String[] args) {
test3();
}
private static void test3 () {
BufferedReader in = null ;
try {
in = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\test.txt"));
StringBuffer sbf = new StringBuffer();
String tmp;
while ((tmp=in.readLine())!=null) {
System.out.println(tmp);
sbf.append(tmp);
}
System.out.println("-------读取完成------");
System.out.println(sbf.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static void test2 () {
InputStream in =null;
try {
in = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\test.txt"));
//缓冲区
byte[] b = new byte[4];
//本次读取长度
int len;
StringBuffer sbf = new StringBuffer();
while((len=in.read(b))!=-1){//把读取的数据放到i中
for (byte c : b) {
System.out.print(c+" ");
}
System.out.println();
String tmp = new String(b,0,len,"UTF-8");
System.out.println("本次读取长度:"+len+"、内容:"+tmp);
sbf.append(tmp);
}
System.out.println("-------读取完成------");
System.out.println(sbf.toString());
//把字节数组转成字符串
//关闭流
in.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}