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

Java:IO流与IO设备

2015-10-28 17:53 441 查看
打印流:PrintWriter和PrintStream

特点:可以直接操作输入流和文件
//例子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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: