java中的setiocn_JAVA IO之输入输出生定向

使用OutputStream向屏幕上输出内容

/**

* 使用OutputStream向屏幕上输出内容

* */

import java.io.*;

class hello {

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

OutputStream out=System.out;

try{

out.write("hello".getBytes());

}catch (Exception e) {

e.printStackTrace();

}

try{

out.close();

}catch (Exception e) {

e.printStackTrace();

}

}

}

输入输出重定向import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.PrintStream;

/**

* 为System.out.println()重定向输出

* */

public class systemDemo{

public static void main(String[] args){

// 此刻直接输出到屏幕

System.out.println("hello");

File file = new File("d:" + File.separator + "hello.txt");

try{

System.setOut(new PrintStream(new FileOutputStream(file)));

}catch(FileNotFoundException e){

e.printStackTrace();

}

System.out.println("这些内容在文件中才能看到哦!");

}

}

【运行结果】:

eclipse的控制台输出的是hello。然后当我们查看d盘下面的hello.txt文件的时候,会在里面看到:这些内容在文件中才能看到哦!

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.PrintStream;

/**

* System.err重定向 这个例子也提示我们可以使用这种方法保存错误信息

* */

public class systemErr{

public static void main(String[] args){

File file = new File("d:" + File.separator + "hello.txt");

System.err.println("这些在控制台输出");

try{

System.setErr(new PrintStream(new FileOutputStream(file)));

}catch(FileNotFoundException e){

e.printStackTrace();

}

System.err.println("这些在文件中才能看到哦!");

}

}

【运行结果】:

你会在eclipse的控制台看到红色的输出:“这些在控制台输出”,然后在d盘下面的hello.txt中会看到:这些在文件中才能看到哦!

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

/**

* System.in重定向

* */

public class systemIn{

public static void main(String[] args){

File file = new File("d:" + File.separator + "hello.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));

}

}

}

【运行结果】:

前提是我的d盘下面的hello.txt中的内容是:“这些文件中的内容哦!”,然后运行程序,输出的结果为:读入的内容为:这些文件中的内容哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值