实例1:
public class PrintStream01 {
public static void main(String[] args) {
try {
//PrintStream 为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。
//PrintStream不同于PrintWriter,PrintStream输出的是字节内容。
//public PrintStream(OutputStream out)创建新的打印流。
PrintStream ps=new PrintStream(new FileOutputStream(new File("e:"+File.separator+"PrintStreamDemo01.txt"),true));
int stuNum=107;
String name="张三";
char sex='M';
float height=175.34f;
//PrintStream对传入的OutputStream及其子类进行装饰,是其实用更加方便。主要是提供了很多Print()和Println()方法。
ps.print(stuNum);
//按照平台的默认字节编码将 String.valueOf(int) 生成的字符串转换为字节,并完全以 write(int) 方法的方式写入这些字节。
ps.println(name);
//按照平台的默认字符编码将字符转换为一个或多个字节,并完全以 write(int) 方法的方式写入这些字节。
ps.println(sex);
ps.println(height);//
ps.close();
System.out.println("向文件中输入数据完毕!");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
实例2:
public class PrintStream02 {
public static void main(String[] args) {
try {
PrintStream ps=new PrintStream(new FileOutputStream(new File("e:"+File.separator+"PrintStreamDemo02.dat"),true));
int stuNum=107;
String name="张三";
char sex='M';
float height=175.34f;
ps.printf("学号:%s---姓名:%s---性别:%c---身高:%f",stuNum,name,sex,height);
System.out.println("向文件中输入数据完毕!");
ps.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
InputStream in=new FileInputStream(new File("e:"+File.separator+"PrintStreamDemo02.dat"));//读取
byte[] b=new byte[1024];
int len=in.read(b);
System.out.println("读取的内容:"+new String(b,0,len));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}