public final static PrintStream out = null; 与 public final static PrintStream out; 的区别???

本文详细解释了Java中静态变量的两种声明方式:带有初始值赋值与不带初始值赋值的区别,指出这两种方式在实际应用中并无不同。

public final static PrintStream out = null;   与   public final static PrintStream out;  的区别???

答:没有区别。

import java.io.*; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class StreamRedirector { public static void main(String[] args) throws Exception { // 1. 备份原始标准流 InputStream originalIn = System.in; PrintStream originalOut = System.out; PrintStream originalErr = System.err; try { // 2. 重定向标准输入(从input.txt读取) FileInputStream fileInput = new FileInputStream("input.txt"); System.setIn(fileInput); // 3. 重定向标准输出(UTF-8编码写入output.txt) FileOutputStream fileOutput = new FileOutputStream("output.txt"); PrintStream newOut = new PrintStream(fileOutput, true, StandardCharsets.UTF_8.name()); System.setOut(newOut); // 4. 重定向标准错误(UTF-8编码写入error.log) FileOutputStream errorOutput = new FileOutputStream("error.log"); PrintStream newErr = new PrintStream(errorOutput, true, StandardCharsets.UTF_8.name()); System.setErr(newErr); // 5. 执行业务方法 executeBusinessLogic(); } finally { // 6. 还原原始标准流(确保在异常时也能执行) System.setIn(originalIn); System.setOut(originalOut); System.setErr(originalErr); } } private static void executeBusinessLogic() { try { // 从重定向后的System.in读取(实际读取input.txt) Scanner scanner = new Scanner(System.in); System.out.println("读取内容: " + scanner.nextLine()); // 模拟业务异常 throw new RuntimeException("业务逻辑异常示例"); } catch (Exception e) { // 异常信息写入error.log(因System.err已重定向) e.printStackTrace(); } } }逐行分析
最新发布
11-14
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值