实现将基本数据类型的数据格式转化为字符串输出。
打印流:PrintStream和PrintWriter。
提供了一系列重载的print()和println()方法,用于多种数据类型的输出。
PrintStream和Printwriter的输出不会抛出IOException异常。
PrintStream和Printwriter有自动flush功能。
Printstream 打印的所有字符都使用平合的默认字符编码转换为字节,在需要写入字符而不是写入字节的情况下,应该使用Printwriter类。
System.out返回的是PrintStream的实例。
代码实现:
/**
* 打印流测试
* 改变系统默认的打印流,使用自定义的打印流,将结果写入文件中
*/
@Test
public void test1() {
//创建打印流
PrintStream printStream = null;
try {
//需要输出的文件print.txt
FileOutputStream fileOutputStream = new FileOutputStream("print.txt");
printStream = new PrintStream(fileOutputStream, true);
//将标准的输出流(控制台输出)改成文件
if (printStream != null) {
System.setOut(printStream);
}
//输出乘法口诀表
for (int i=1; i<=9; i++) {
for (int j=1; j<=i; j++) {
System.out.print(i+"*"+j+"="+i*j+"\t");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭打印流
if (printStream != null) {
try {
printStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
结果: