System类中名为out的字段表示一个标准输出Stream,是PrintStream类的一个对象。
它的 println() 方法接受任何 a 值(任何 Java 有效类型),打印它并终止该行。默认情况下,控制台(屏幕)是标准输出流(System.out)。 in) 在 Java 中,每当我们将任何 String 值传递给 System.out.prinln() 方法时,它都会在控制台上打印给定的 String。
重定向 System.out.println()
java中System类的setout()方法接受PrintStream类的对象并将其设置为新的标准输出流。
因此,要将 System.out.println() 输出重定向到文件 -
-
创建 File 类的对象。
li> 通过将上面创建的 File 对象作为参数传递来实例化一个 PrintStream 类。
示例
import java.io.File; import java.io.IOException; import java.io.PrintStream; public class SetoutExample { public static void main(String args[]) throws IOException { //Instantiating the File class File file = new File("D:\sample.txt"); //Instantiating the PrintStream class PrintStream stream = new PrintStream(file); System.out.println("From Now on "+file.getAbsolutePath()+" will be your console"); System.setout(stream); //Printing values to file System.out.println("Hello, how are you"); System.out.println("Welcome to Tutorialspoint"); } }
输出
From Now on D:\sample.txt will be your console
以上就是在Java中将System.out.println()的输出重定向到文件的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。