PrintStream
为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。它还提供其他两项功能。与其他输出流不同,
PrintStream
永远不会抛出
IOException
;而是,异常情况仅设置可通过
checkError
方法测试的内部标志。另外,为了自动刷新,可以创建一个
PrintStream
;这意味着可在写入 byte 数组之后自动调用
flush
方法,可调用其中一个
println
方法,或写入一个换行符或字节 (
'\n'
)。
PrintStream
打印的所有字符都使用平台的默认字符编码转换为字节。在需要写入字符而不是写入字节的情况下,应该使用
PrintWriter
类。
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"))) ;
//以下代码实际上是将FileOutputStream类的功能包装类一下,这样的设计在Java中我们称之为装饰设计
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.close() ;
}
};
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.close() ;
}
};
如果觉得以上代码中%不好记可以将其全部写成%s.看代码
import java.io.* ;
public class PrintDemo03{
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;年龄:%s;成绩:%s;性别:%s",name,age,score,sex) ;
ps.close() ;
}
};
public class PrintDemo03{
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;年龄:%s;成绩:%s;性别:%s",name,age,score,sex) ;
ps.close() ;
}
};
©著作权归作者所有:来自51CTO博客作者海源溪的原创作品,如需转载,请注明出处,否则将追究法律责任
0
收藏
转载于:https://blog.51cto.com/haiyuanxi/934504