Java 流-打印流&数据流
PrintStream
1.System.out 和 System.err 都是PrintStream的实例
2.PrintStream的方法都不用抛出IOException异常
3.打印流无需类型转换,自动转成String类型,但缓冲流需要类型转换(使用缓冲流只能写入字符串)
4.使用打印流时会自动转成String类型,会失去数据原有的类型
import java.io.*;
import java.util.Date;
public class TestPrint {
public static void main(String[] args) throws IOException {
//1.PrintStream ps = System.out; //或.err
//2.PrintStream ps = new PrintStream(new FileOutputStream("D:\\print.txt"));//写入文件
PrintWriter ps = new PrintWriter(new FileOutputStream("D:\\print.txt"));//需要手动刷下缓存
ps.println("Love you 3000 times");
ps.println(true);
ps.println(9999);
ps.println(new Date(1000));
ps.close();
ps.flush();
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\a.txt"));
bw.write("Hello");
bw.write(99.5); //不准换会报错
bw.write(new Date());
}
}
数据流
1.提供了可以存取的所有Java基本数据类型
2.处理流,只针对字节流,二进制文件
3.输入流链和输出流链
4.关闭时之关闭上层流
import java.io.*;
public class TestData {
public static void main(String[] args) throws IOException {
write();
read();
}
public static void read() throws IOException {
//(1)数据源
FileInputStream fis = new FileInputStream("D:\\a.txt");
//(2)提高读写效率
BufferedInputStream bis = new BufferedInputStream(fis);
//(3)数据流
DataInputStream dis = new DataInputStream(bis);
//前三步可合成一句
// DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("D:\\a.txt")));
//(4)读数据
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
System.out.println(dis.readUTF());
dis.close();
}
public static void write() throws IOException {
//(1)目的地
FileOutputStream fos = new FileOutputStream("D:\\a.txt");
//(2)缓冲流提高效率
BufferedOutputStream bos = new BufferedOutputStream(fos);
//(3)数据流,增加对Java基本数据类型和String的处理
DataOutputStream dos = new DataOutputStream(bos);
//(4)写入数据 //写入的字符是它原来的模样
dos.writeInt(98);
dos.writeDouble(99.5);
dos.writeBoolean(true);
dos.writeChar('a');
dos.writeUTF("Love");
//(5)关闭
if(dos!=null)
dos.close();
}
}