1.System.out输出重定向
public static void main(String[] args) {
// 此刻直接输出到屏幕
System.out.println("hello");
File file = new File("C:/Users/liuyan/Desktop/test/one.txt");
try {
System.setOut(new PrintStream(new FileOutputStream(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("这些内容在文件中才能看到哦!");
}
2.System.err 重定向
public static void main(String[] args){
File file = new File("C:/Users/liuyan/Desktop/test/one.txt");
System.err.println("这些在控制台输出");
try{
System.setErr(new PrintStream(new FileOutputStream(file)));
}catch(FileNotFoundException e){
e.printStackTrace();
}
System.err.println("这些在文件中才能看到哦!");
}
3.System.in 输入重定向
public static void main(String[] args) {
File file = new File("C:/Users/liuyan/Desktop/test/one.txt");
if (!file.exists()) {
return;
} else {
try {
System.setIn(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] bytes = new byte[1024];
int len = 0;
try {
len = System.in.read(bytes); //不在从控制台读取
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("读入的内容为:" + new String(bytes, 0, len));
}
}
4.获取系统默认编码
System.out.println("系统默认编码为:" + System.getProperty("file.encoding"));