📅  最后修改于: 2023-12-03 14:42:15.783000             🧑  作者: Mango
PrintStream类是Java中的标准输出流类之一,它提供了方便的输出方法,可以将数据输出到控制台或者文件中。下面我们来详细了解一下PrintStream类的相关内容。
PrintStream类有多个构造方法,其中较常用的有以下两种:
// 构造方法一:创建一个新的PrintStream对象,将其输出到标准输出流
public PrintStream(OutputStream out)
// 构造方法二:创建一个新的PrintStream对象,将其输出到指定的文件
public PrintStream(String fileName) throws FileNotFoundException
PrintStream类提供了多个输出方法,可以输出不同类型的数据。以下是PrintStream类的常用方法:
print
方法可以输出不同类型的数据,并且不会添加换行符。以下是print
方法的用法示例:
// 输出字符串 "hello world!"
System.out.print("hello world!");
// 输出整数 123
System.out.print(123);
// 输出浮点数 3.14
System.out.print(3.14);
println
方法与print
方法类似,但会在最后自动添加一个换行符。以下是println
方法的用法示例:
// 输出字符串 "hello world!" 并换行
System.out.println("hello world!");
// 输出整数 123 并换行
System.out.println(123);
// 输出浮点数 3.14 并换行
System.out.println(3.14);
printf
方法可以按照指定的格式输出数据。以下是printf
方法的用法示例:
// 输出浮点数 3.14159,保留两位小数
System.out.printf("%.2f", 3.14159);
// 输出字符串 "hello world!" 两个空格,再输出整数 123
System.out.printf("hello world! %d", 123);
以下代码展示了如何使用PrintStream类将数据输出到控制台和文件中:
import java.io.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
// 输出到控制台
PrintStream console = System.out;
console.println("hello world!");
// 输出到文件
PrintStream file = new PrintStream(new FileOutputStream("output.txt"));
file.println("hello world!");
file.close();
}
}
以上代码中,我们使用System.out
对象将数据输出到控制台。然后我们创建了一个新的PrintStream对象,将数据输出到"output.txt"文件中。最后,我们使用close
方法关闭了文件输出流。