Java:IO流与IO设备
2015-10-28 17:53
441 查看
打印流:PrintWriter和PrintStream
特点:可以直接操作输入流和文件
//例子1:使用PrintStream将格式化的日期打印到文件中
//例子2:使用printStream将系统信息properties打印到文件中
//例子3:使用printStream打印流打印数据时对异常的处理
读取键盘录入:System.out、System.in
System.out:对应的是标准输出流设备,控制台(屏幕)
System.in:对应的是标准输入设备,键盘
需求:通过键盘录入数据,当录入一行数据后,将就改行数据进行打印,
如果录入的数据是over,那么停止录入。
//例子4:
特点:可以直接操作输入流和文件
//例子1:使用PrintStream将格式化的日期打印到文件中
import java.io.*; import java.util.*; import java.text.*; class ExceptionInfo { public static void main(String[] args)throws IOException { try { int[] arr = new int[2]; System.out.println(arr[3]); } catch(Exception e) { try { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String s = sdf.format(d); PrintStream ps = new PrintStream("f:\\myfile\\IOException.log"); ps.println(s); System.setOut(ps); } catch(Exception e1) { throw new RuntimeException("日志文件创建失败!"); } e.printStackTrace(System.out); } } }
//例子2:使用printStream将系统信息properties打印到文件中
import java.util.*; import java.io.*; import java.text.*; class SystemInfo { public static void main(String[] args)throws IOException { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String s = sdf.format(d); Properties p = System.getProperties(); PrintStream ps = new PrintStream("f:\\myfile\\SystemInfo.txt"); System.setOut(ps); ps.println(s); p.list(ps); ps.close(); } }
//例子3:使用printStream打印流打印数据时对异常的处理
import java.io.*; import java.util.*; import java.text.*; class ExceptionInfo { public static void main(String[] args)throws IOException { try { int[] arr = new int[2]; System.out.println(arr[3]); } catch(Exception e) { try { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String s = sdf.format(d); PrintStream ps = new PrintStream("f:\\myfile\\IOException.log"); ps.println(s); System.setOut(ps); } catch(Exception e1) { throw new RuntimeException("日志文件创建失败!"); } e.printStackTrace(System.out); } } }
读取键盘录入:System.out、System.in
System.out:对应的是标准输出流设备,控制台(屏幕)
System.in:对应的是标准输入设备,键盘
需求:通过键盘录入数据,当录入一行数据后,将就改行数据进行打印,
如果录入的数据是over,那么停止录入。
//例子4:
import java.io.*; class ReadInDemo { public static void main(String[] args)throws IOException { InputStream in = System.in; //从键盘输入数据 StringBuilder sb = new StringBuilder(); int ch = 0; while(true) { ch = in.read(); if(ch=='\r') continue; if(ch=='\n') { String s = sb.toString(); if("over".equals(s)) break; System.out.println(s.toUpperCase()); sb.delete(0,sb.length()); } else sb.append((char)ch); } in.close(); } }
相关文章推荐
- java反射--Field
- Java栈的模拟实现
- J2EE框架(Struts&Hibernate&Spring)的理解
- Sending e-mail with Spring MVC--转载
- 我理解中的简单工厂模式
- JAVA----关键字用法
- Java NIO系列教程(二) Channel
- Java:IO流之字符流缓冲区详解
- Eclipse项目导入到Android studio中
- Spring-Bean的生命周期
- Java中如何遍历Map对象的4种方法
- 美图2016校招java编程
- java 接口回调
- java Vamei快速教程19 嵌套类
- Java解析eml内容和附件
- Java:IO流之字符流Reader、Writer详解
- Spring MVC 中的 forward 和 redirect
- java Vamei快速教程18 容器
- java学习笔记
- Spring Class MongoTemplate详解