通过使用PrintStream实例输出到文件
原有System.out.println 现改为PrintStream类型的实例.println以完成输出到文件
完整代码
代码语言:javascript复制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");
}
}
使用System的setOut方法重定向
通过向setOut方法PrintStream实例进行重新定向到文件 重新定向到控制台:FileDescriptor.out(将原来的file对象替换为这个)
完整代码
代码语言:javascript复制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");
}
}
将字节流输入转为字符流,运用字符流方法进行操作
完整代码
代码语言:javascript复制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());
}
}