1.关系
InputStream&OutputStream是CP(couple)。
Reader&Writer是CP(couple)。
InputStream&Reader是GM(闺蜜)。
OutputStream&Writer是JY(基友)。
2.Reader类
主要的方法:
1)int read() 从输入流中读取单个字符,返回所读取的字符数据(字符数据可以直接转换为int类型)
2)
int read(char[] cbuf) 从输入流中最多读取cbuf.length个数据字符,并将其存储在字符数组cbuf中,返回实际读取的字符数。
3)
int read(char[] cbuf,int off,int len) 从输入流中最多读取cbuf.length个数据字符,并将其存储在字符数组cbuf中,放入数组cbuf中时,并不是从数组起点开始,而是从off位置开始,返回实际读取的字符数。
3.Writer类
主要的方法:
1)void write(String str) 将str字符串里包含的字符输出到指定输出流中
2)void write(String str,int off,int len) 将str字符串里从off位置开始,长度为len的字符输出到指定输出流中。
4.Reader&Writer实例
public class FileTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("zhangmq.txt");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Writer fw = new FileWriter(file);
fw.write("what's your name?");
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Reader fr = new FileReader(file);
char[] buf = new char[60];
int count = 0;
try {
while((count = fr.read(buf))!=-1){
System.out.println(new String(buf,0,count)); //在控制台输出
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在控制台输出结果:what's your name?
5.InputStream类
主要方法:
1)int read()
读入一个字节,并返回读入的字节。在遇到输入源结尾时返回-1。
2)int read(byte[] b) 读入一个字节数组,并返回实际读入的字节数。在遇到流的结尾时返回-1。
最多读入b.length()个字节。
读入字节到数组中。
3)
int read(byte[] b,int off,int len)
读入一个字节数组,并返回实际读入的字节数。在遇到流的结尾时返回-1。
off:第一个读入字节应该被放置的位置在b中的偏移量。即从字节数组中的哪个位子开始。
len:读入字节的最大数量。
(4)void close() 关闭输入流
(5)int available() 返回在不阻塞的情况下可用的字节数。
6.OutputStream类
主要方法:
1)void write(int b) 向某个输出位置写出b个字节。
2)void write(byte[] b)
3)void write(byte[] b,int off,int len)写出所有字节或是某个范围的字节到数组b中。
4)
void close() 关闭输出流
5)void flush() 清空输出流,也即是将所有缓冲的数据发送到目的地。
7.InputStream&OutputStream实例
public class FileTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("zhouhy.txt");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
OutputStream fos = new FileOutputStream(file);
String str = "zhouhaoyu";
byte[] b = str.getBytes();
try {
fos.write(b);
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream fis = new FileInputStream(file);
int count;
byte[] b = null;
try {
count = fis.available();
if(count>0){
b = new byte[count];
fis.read(b);
}
fis.close();
System.out.println(new String(b,0,count));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}