在整个IO包中,打印流是输出信息最方便的类,主要包含字节打印流和字符打印流。打印流提供了非常方便的打印功能,可以打印任何的数据类型,例如:小树、证书、字符串等。
使用PrintStream输出信息
import java.io.* ;
public class PrintDemo01{
public static void main(String arg[]) throws Exception{
PrintStream ps = null ; // 声明打印流对象
// 如果现在是使用FileOuputStream实例化,意味着所有的输出是向文件之中
ps = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "test.txt"))) ;
ps.print("hello ") ;
ps.println("world!!!") ;
ps.print("1 + 1 = " + 2) ;
ps.close() ;
}
};
格式化输出
import java.io.* ;
public class PrintDemo02{
public static void main(String arg[]) throws Exception{
PrintStream ps = null ; // 声明打印流对象
// 如果现在是使用FileOuputStream实例化,意味着所有的输出是向文件之中
ps = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "test.txt"))) ;
String name = "李兴华" ; // 定义字符串
int age = 30 ; // 定义整数
float score = 990.356f ; // 定义小数
char sex = 'M' ; // 定义字符
ps.printf("姓名:%s;年龄:%d;成绩:%f;性别:%c",name,age,score,sex) ;
//ps.printf("姓名:%s;年龄:%s;成绩:%s;性别:%s",name,age,score,sex) ;
ps.close() ;
}
};
如果记不住该使用哪种格式,可以都是用%s代替