System 输入输出重定向
发布日期:2021-06-30 21:07:53 浏览次数:2 分类:技术文章

本文共 1292 字,大约阅读时间需要 4 分钟。

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"));

 

 

 

转载地址:https://liuyan.blog.csdn.net/article/details/81189352 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:File 类小结
下一篇:SequenceInputStream 合并流,同时读多个文件 例子

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月28日 17时59分13秒