原有System.out.println 现改为PrintStream类型的实例.println以完成输出到文件
package cn.hxh.io.other;
import java.io.*;
public class PrintStreamDemo01 {
public static void main(String[] args) throws IOException {
System.out.println("test");
PrintStream ps = System.out;
ps.println("111");
File src = new File("D:/aa/a.txt");
ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(src)), true);
ps.println("test1");
}
}
通过向setOut方法PrintStream实例进行重新定向到文件 重新定向到控制台:FileDescriptor.out(将原来的file对象替换为这个)
package cn.hxh.io.other;
import java.io.*;
import java.util.*;
public class SystemDemo01 {
public static void main(String[] args) throws IOException {
// Scanner in = new Scanner(new BufferedInputStream(new FileInputStream(new File("D:/aa/a.txt"))));
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("d:/aa/a.txt"))), true));
System.out.println();
System.out.println("test");
System.out.println("err");
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)), true));
System.out.println("err");
}
public static void test1() throws IOException {
Scanner in = new Scanner(new BufferedInputStream(new FileInputStream(new File("D:/aa/a.txt"))));
System.out.println(in.nextLine());
System.out.println("test");
System.err.println("err");
}
}
package cn.hxh.io.other;
import java.io.*;
public class bufferedIn {
public static void main(String[] args) throws IOException {
InputStream is = System.in;
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
System.out.println(bis.readLine());
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有