您的位置:首页 > 编程语言 > Java开发

Java IO笔记:标准IO

2013-09-07 16:09 218 查看
1.标准输入和输出

标准IO是指程序的输入和标准输出,用户和程序之间、程序和程序之间的交流都可以通过标准IO实现。Java中使用System.in(输入),System.out(输出)和System.err(错误输出)来提供程序的输入和输出。

2.读取输入数据

public class Echo {

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

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;

while ((s = in.readLine()) != null && s.length() > 0) {
System.out.println(s);
}

}

}


3.重定向输入和输出
public class RedirectTest {

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

//保存out,后面使用
PrintStream con = System.out;

BufferedInputStream in = new BufferedInputStream(new FileInputStream(
"test.txt"));

PrintStream out = new PrintStream(new BufferedOutputStream(
new FileOutputStream("test.out")));

//重定向输入到文件输入流 in
System.setIn(in);

//重定向输出到文件输出流
System.setOut(out);
System.setErr(out);

BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
String s;
while((s = input.readLine()) != null){
System.out.println(s);
}

out.close();

//输出重定向默认的
System.setOut(con);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: