输出流(写入数据)
a. 字节输出流
OutputStram
输出流的父类
FileOutputStream: 继承OutputStream
方法:
OutputStream os=new FileOutputStream("dos.txt");
os.write("asdf".getBytes());
os.close();
b. 字符输出流
Writer
abstract class Writer implements Appendable, Closeable, Flushable
应使用它们的子类来创建实体对象
子类:
FileWrite----继承---->OutputStreamWrite
FileWriter fd=new FileWriter("dos.txt");
fd.write("FileWriter");
fd.close();
c. 缓冲区输出流
BufferedWriter --继承--> Writer
Writer w=new FileWriter("dos.txt");
BufferedWriter bw1=new BufferedWriter(w);
bw1.write("BufferedWriter");
bw1.close();
BufferedOutputStream 继承FilterOutputStream
OutputStream ops=new FileOutputStream("dos.txt");
BufferedOutputStream bw=new BufferedOutputStream(ops);
bw.write("BufferedOutputStream".getBytes());
bw.close();
d.内存输出流(特殊流) 需要先写再读
ByteArrayOUtputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 写数据
for (int x = 0; x < 10; x++) {
baos.write(("hello" + x).getBytes());
}
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
int s=0;
while((s=bais.read())!=-1)
{
System.out.print((char)s);
}
CharArrayStream
CharArrayWriter baos = new CharArrayWriter();
String str="asdfgasgretfgertgergasdrg";
// 写数据
for (int x = 0; x < 2; x++)
{
baos.write(str.toCharArray());
}
CharArrayReader bais=new CharArrayReader(baos.toCharArray());
int s=0;
while((s=bais.read())!=-1)
{
System.out.print((char)s);
}
StringReader
StringWriter baos = new StringWriter();
String str="asdfgasgretfgertgergasdrg";
// 写数据
for (int x = 0; x < 2; x++)
{
baos.write(str);
}
StringReader bais=new StringReader(baos.toString());
int s=0;
while((s=bais.read())!=-1)
{
System.out.print((char)s);
}
e. 数据输出流
DataOutputStream
// 创建数据输出流对象
DataOutputStream dos = new DataOutputStream(new FileOutputStream(
"dos.txt"));
// 写数据了
dos.writeByte(10);
dos.writeShort(100);
dos.writeInt(1000);
dos.writeLong(10000);
dos.writeFloat(12.34F);
dos.writeDouble(12.56);
dos.writeChar('a');
dos.writeBoolean(true);
// 释放资源
dos.close();
f.转换输出流(字符转字节流)
OutputStreamReader
OutputStream ops=new FileOutputStream("dos.txt");
OutputStreamWriter osw=new OutputStreamWriter(ops);
osw.write("123");
osw.close();
g. 打印输出流(只能写不能读)
(1)字节打印流,字符打印流
(2)特点:
A:只操作目的地,不操作数据源
B:可以操作任意类型的数据
C:如果启用了自动刷新,在调用println()方法的时候,能够换行并刷新
D:可以直接操作文件
问题:哪些流可以直接操作文件呢?
看API,如果其构造方法能够同时接收File和String类型的参数,一般都是可以直接操作文件的
(3)复制文本文件
BufferedReader br = new BufferedReader(new FileReader("a.txt"));
PrintWriter pw = new PrintWriter(new FileWriter("b.txt"),true);
String line = null;
while((line=br.readLine())!=null) {
pw.println(line);
}
pw.close();
br.close();