毕向东_Java基础视频教程第19天_IO流(20~22)

时间:2023-02-11 12:50:41

第19天-20-IO流(改变标准输入输出设备)

static void setIn(InputStream in)   Reassigns the "standard" input stream.

static void setOut(PrintStream out)  Reassigns the "standard" output stream.

package bxd;

import java.io.*;

public class TransStreamDemo3 {
public static void main(String[] args) throws IOException {

// 并不常用
System.setIn(new FileInputStream("s.txt"));
System.setOut(
new PrintStream("out.txt"));

BufferedReader bufr
= new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufw
= new BufferedWriter(new OutputStreamWriter(System.out));

String line;
while ((line = bufr.readLine()) != null) {
if ("eof".equals(line)) break;
bufw.write(line);
bufw.newLine();
bufw.flush();
}
bufr.close();
bufw.close();
}
}

第19天-21-IO流(异常的日志信息)

void printStackTrace(PrintStream s)  Prints this throwable and its backtrace to the specified print stream.

package bxd;

import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExceptionInfo {
public static void main(String[] args) {
try {
// 数组越界访问
int[] array = new int[2];
System.out.println(array[
3]);
}
catch (Exception e) {
PrintStream printStream
= null;
String time
= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
try {
printStream
= new PrintStream("ExceptionInfo.txt");
printStream.println(time);
//printStream.write(time.getBytes());
} catch (Exception ex) {
throw new RuntimeException("日志文件创建失败");
}
e.printStackTrace(printStream);
}
// 实际项目中会使用log4j.
}
}
 

第19天-22-IO流(打印系统信息)

static Properties getProperties()   Determines the current system properties.

package bxd;

import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;

public class SystemInfo {
public static void main(String[] args) throws IOException {
Properties prop
= System.getProperties();
prop.list(
new PrintStream("Sysinfo.txt"));
}
}