Java教程

Java PrintStream

Java PrintStream类提供了将数据写入另一个流的方法。 PrintStream类自动刷新数据,因此无需调用flush()方法。而且,其方法不会引发IOException。

类声明

让我们看看Java.io.PrintStream类的声明:
public class PrintStream extends FilterOutputStream implements Closeable. Appendable

PrintStream类的方法

方法 说明
void print(boolean b) 它将打印指定的布尔值。
void print(char c) 它将打印指定的char值。
void print(char [] c) 它将打印指定的字符array值。
void print(int i) 它将打印指定的int值。
void print(长l) 它将打印指定的long值。
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) 它将打印指定的double值并终止行。
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.lidihuo;
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 的内容
2016Hello JavaWelcome to Java

使用java PrintStream类的printf()方法的示例:

让我们看看使用 printf()通过格式说明符打印整数值的简单示例 java.io.PrintStream 类的strong>方法。
class PrintStreamTest{
    public static void main(String args[]){
        int a=19;
        System.out.printf("%d",a);
    //Note: out is the object of printstream }
}
输出
19
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4