Java教程-Java PrintStream类

Java PrintStream类
PrintStream类提供了向另一个流写入数据的方法。PrintStream类会自动刷新数据,因此无需调用flush()方法。此外,它的方法不会抛出IOException。
类声明
让我们看一下Java.io.PrintStream类的声明:
public class PrintStream extends FilterOutputStream implements Closeable. Appendable
PrintStream类方法
Method | Description |
---|---|
void print(boolean b) | 它打印指定的布尔值。 |
void print(char c) | 它打印指定的 char 值。 |
void print(char[] c) | 它打印指定的字符数组值。 |
void print(int i) | 它打印指定的 int 值。 |
void print(long l) | 它打印指定的长值。 |
void print(float f) | 它打印指定的浮点值。 |
void print(double d) | 它打印指定的双精度值。 |
void print(String s) | 它打印指定的字符串值。 |
void print(Object obj) | 它打印指定的对象值。 |
void println(boolean b) | 它打印指定的布尔值并终止该行。 |
void println(char c) | 它打印指定的 char 值并终止该行。 |
void println(char[] c) | 它打印指定的字符数组值并终止该行。 |
void println(int i) | 它打印指定的 int 值并终止该行。 |
void println(long l) | 它打印指定的 long 值并终止该行。 |
void println(float f) | 它打印指定的浮点值并终止该行。 |
void println(double d) | 它打印指定的双精度值并终止该行。 |
void println(String s) | 它打印指定的字符串值并终止该行。 |
void println(Object obj) | 它打印指定的对象值并终止该行。 |
void println() | 它仅终止该行。 |
void printf(Object format, Object... args) | 它将格式化的字符串写入当前流。 |
void printf(Locale l, Object format, Object... args) | 它将格式化的字符串写入当前流。 |
void format(Object format, Object... args) | 它使用指定格式将格式化字符串写入当前流。 |
void format(Locale l, Object format, Object... args) | 它使用指定格式将格式化字符串写入当前流。 |
java PrintStream类示例
在此示例中,我们只是打印整数和字符串值。
package com.javatpoint;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");
PrintStream pout=new PrintStream(fout);
pout.println(2016);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
System.out.println("Success?");
}
}
输出
Success...
文本文件testout.txt的内容如下所示:
2016
Hello Java
Welcome to Java
使用java PrintStream类的printf()方法的示例:
让我们看一下使用java.io.PrintStream类的printf()方法使用格式说明符打印整数值的简单示例。
class PrintStreamTest{
public static void main(String args[]){
int a=19;
System.out.printf("%d",a); //注意:out 是 printstream 的对象
}
}
输出
19