PrintStream对象其实我们用的算比较多的,怎么说呢,我们平时使用System.out.println();方法其实里面的System.out返回的对象就是PrintStream对象
import java.io.File;
import java.io.FileNotFoundException;import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamTest {
public static void main(String[] args) {
PrintStream ps = null;
try {
ps = new PrintStream(new FileOutputStream(new File("F:" + File.separator + "javatest" + File.separator + "printstreamtest.txt")));
ps.print(true);
ps.print('x');
ps.print(new char[] {'a','b','c','d'});
ps.print(1.023);
ps.print(1.01f);
ps.print(2);
ps.print(1000000000);
ps.print("i am a gay!");
// 私有内部类的实例化
PrintStreamTest.User user = new PrintStreamTest().new User("zhangsan", 20);
ps.print(user);
// 换行
ps.println();
ps.println(true);
ps.println('x');
ps.println(new char[] {'a','b','c','d'});
ps.println(1.023);
ps.println(1.01f);
ps.println(2);
ps.println(1000000000);
ps.println("i am a gay!");
ps.println(user);
// 格式化输出
ps.printf("name %s . age %d", "zhangsan",20);
// 不用显示的调用,这个方法会自动调用,也就是ps每调用一次print,文件中已经存在值了
ps.flush();
ps.println();
ps.append("AAAAAAAAAAAAAAAAA\r\n");
CharSequence cs = "hello world\r\n";
ps.append(cs);
ps.append(cs, 0, 5);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
ps.close();
}
}
private class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "my name is " + this.name + ", i am " + this.age;
}
}
}
文件输出结果如下:
truexabcd1.0231.0121000000000i am a gay!my name is zhangsan, i am 20
true
x
abcd
1.023
1.01
2
1000000000
i am a gay!
my name is zhangsan, i am 20
name zhangsan . age 20
AAAAAAAAAAAAAAAAA
hello world
hello