1.將輸出結(jié)果輸出到txt文件
直接安排代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//導(dǎo)包 import java.io.filenotfoundexception; import java.io.printstream; public class test { public static void main(string[] args) throws filenotfoundexception { // 創(chuàng)建一個(gè)打印輸出流,輸出的目標(biāo)是d盤下的1.txt文件 printstream ps = new printstream( "d:\\1.txt" ); //可能會(huì)出現(xiàn)異常,直接throws就行了 system.setout(ps); //把創(chuàng)建的打印輸出流賦給系統(tǒng)。即系統(tǒng)下次向 ps輸出 system.out.println( "看看我在哪里?" ); system.out.println( "==============" ); system.out.println( "我在d盤下的1.txt文件中去了。" ); ps.close(); } } |
運(yùn)行結(jié)果:
2.將輸出結(jié)果重新輸出到屏幕
其實(shí)代碼跟前面只有一點(diǎn)出入。
強(qiáng)調(diào):
在把系統(tǒng)的輸入方向改變時(shí),如果還要重新回到系統(tǒng)默認(rèn)輸出的話,就一定要在改變之前保存原來系統(tǒng)的輸出方向。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
//導(dǎo)包 import java.io.filenotfoundexception; import java.io.printstream; public class test { public static void main(string[] args) throws filenotfoundexception { // 創(chuàng)建一個(gè)打印輸出流,輸出的目標(biāo)是d盤下的1.txt文件 printstream out = system.out; // 先保存系統(tǒng)默認(rèn)的打印輸出流緩存 //一定要先保存系統(tǒng)最初的打印輸出,不然后面就改不回來了!!! printstream ps = new printstream( "d:\\1.txt" ); //可能會(huì)出現(xiàn)異常,直接throws就行了 system.setout(ps); //把創(chuàng)建的打印輸出流賦給系統(tǒng)。即系統(tǒng)下次向 ps輸出 system.out.println( "看看我在哪里?" ); system.out.println( "==============" ); system.out.println( "我在d盤下的1.txt文件中去了。" ); ps.close(); system.setout(out); //把打印輸出流還給系統(tǒng) system.out.println( "我又回到屏幕啦!" ); system.out.println( "哈哈哈哈哈啊哈" ); } } |
運(yùn)行結(jié)果:
總結(jié)
到此這篇關(guān)于將java程序的輸出結(jié)果寫入文件的文章就介紹到這了,更多相關(guān)java程序輸出結(jié)果寫入文件內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/nxj_climb/article/details/113619816