黑马程序员———IO

来源:互联网 发布:java短信群发源码 编辑:程序博客网 时间:2024/05/01 16:58

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

System:类中的方法和属性都是静态的。

out:标准输出,默认是控制台。

In:标准输入,默认是键盘

获取系统属性信息:Properties getProperties()

System中常用字段、方法:

字段:

static InputStream in  “标准”输入流 对应的是键盘

static PrintStream out “标准”输出流,对应的是控制台

方法:

static Properties getProperties(); 确定当前的系统属性

static String getProperty (String key) 获取指定键指示的系统属性

static String setProperty(String key,String value)设置指定键指示的系统属性

练习代码:

import java.util.*;public class SystemDemo {public static void main(String[] args) {//获得系统属性Properties pro = System.getProperties();        //用高级for循环取出值Set<Object> set = pro.keySet();for(Object obj : set){System.out.println(obj+"::"+pro.getProperty((String) obj));}//自定义系统属性pro.setProperty("lisi", "jldfj");//打印指定键值的属性值System.out.println(pro.get("os.name"));System.out.println(pro.get("lisi"));}}

Runtime: 每个Java应用程序都有一个Runtime类实例,使应用程序能够与其运行环境相连接。可以通过getRuntime方

法获取当前运行时。

方法:

static Runtime getRuntime() 返回与当前Java程序相关联的运行时

Process exec(String command) 在单独的进程中执行指定的字符串命令

示例代码:

//获取运行时Runtime rt = Runtime.getRuntime();//执行windows程序rt.exec("D:\\暴风影音\\BaofengPlatform.exe");

Date

构造函数 Date()分配Date对象并初始化此对象,以表示分配它的时间(精确到毫秒)

SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期--->文本)、解析(文本---->日期)和规范化。

常用构造函数:SimpleDateFormat(String pattern)用给定的模式和默认语言环境的日期格式符号构造 SimpleDateFormat

常用方法:

String format(Date Date) 将一个Date格式化为日期/时间字符串。

示例代码:

                Date d = new Date();System.out.println(d);//打印当前时间//将模式封装到SimpleDateFormat对象中SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日  hh:mm:ss");//调用format方法让模式格式化指定Date对象String time =sdf.format(d);System.out.println(time);

Calender

常用方法:

abstract void add(int Field, int amount)根据日历的规则,为给定的日历字段添加或减去指定的时间量

static Calender getInstance() 使用默认的时区和语言环境获得一个日历

int get(int field) 返回给定字段的值

void set(int year,int month,int date)设置日历字段YEAR、MONTH、和DAY_OF_MONTH的值

常用字段:

static int YEAR  年

static int MONTH 月

static  int DAY_OF_MONTH 一个月中的某天

static int DAY_OF_WEEK 一星期中的某天

static int HOUR 上午或下午得小时

static  int HOUR_OF_DAY 一天中的小时

static int MINUTE 一小时中的分钟

static  int SECOND 一分钟中的秒

练习代码:

import java.util.*;public class CalenderDemo {public static void main(String[] args) {Calendar ca = Calendar.getInstance();//设置日期ca.set(2001, 2, 2);//将现在的ca年份往后推100年ca.add(Calendar.YEAR, 100);//打印输出print(ca);}public static void print(Calendar ca){ String[] str = {"1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"};//自定义月份数组String[] str1 = {" ","星期日","星期一","星期二",//自定义星期数组"星期三","星期四","星期五","星期六"};//获得月int month = ca.get(Calendar.MONTH);//获得星期int week = ca.get(Calendar.DAY_OF_WEEK);//打印输出System.out.println(ca.get(Calendar.YEAR)+"年"+str[month]+ca.get(Calendar.DAY_OF_MONTH)+"日"+str1[week]);}}

 

IO

IO流用来处理设备之间的数据传输

Java对数据的操作是通过流的方式

Java用于操作流的对象都在IO包中

流按操作数据分为两种:字节流与字符流

流按流向分为:输入流,输出流

字符流是为了处理文字数据 可以指定编码表

 

字节流的抽象基类:

InputStream OutputStream

字符流的抽象基类:

Reader Writer

由这四个类派生出来的子类名称都是以其父类名作为子类名的后缀

示例一:在硬盘上创建一个文件并写入一些文字数据

import java.io.*;public class IODemo1 {public static void main(String[] args)throws IOException {//创建一个FileWriter对象。该对象一被初始化就必须要明确被操作的文件。//而且该文件会被创建到指定目录下。如果该目录下已有同名文件,将被覆盖。//其实该步就是在明确数据要存放的目的地FileWriter fw = new FileWriter("d:\\a.txt");//调用write方法,将字符串写入到流中fw.write("jlsjlsfjssjl");        //刷新流对象的缓冲中的数据,将数据刷到目的地中fw.flush();//关闭流资源,但是关闭之前会刷新一次内部的缓冲中的数据,将数据刷到目的地中    fw.close();}<span style="font-size:18px;">}</span>

其中flush和close的区别:flush刷新后,流可以继续使用,close刷新后,会将流关闭。

IO的异常处理,示例代码:

import java.io.*;public class IODemo2 {public static void main(String[] args) {FileWriter fw = null;try{//新建FileWriter对象fw = new FileWriter("d:\\b.txt");char[] ch ={'a','b','c','d','e'};//写入fw.write(ch);}catch(IOException e){throw new RuntimeException();}finally{try{if(fw!=null)//先判读流是否为空fw.close();//无论如何要将流关闭 所以将关闭放到finally语句中 一定可以执行}catch(IOException e){throw new RuntimeException();}}}}

数据读取流:

示例代码:

第一种方式 一个一个字符读


 

import java.io.*;public class IODemo3 {public static void main(String[] args) throws IOException{//创建一个文件读取流对象,和指定名称的文件相关联//要保证该文件时已经存在的,如果不存在,会发生异常FileNotFoundExceptionFileReader fr = new FileReader("d:\\b.txt");//调用读取流对象的read方法//read():一次读一个字符。而且会自动往下读int ch = 0;while((ch = fr.read())!= -1){System.out.println((char)ch);}fr.close();}}

第二种方式 先读到一个字符数组缓存

import java.io.*;public class IODemo4 {public static void main(String[] args)throws IOException{//定义一个FileReader对象FileReader fr = new FileReader("d:\\b.txt");//定义一个字符数组,用于存储读到的字符//该read(char[])返回读到的字符数char[] buf = new char[1024];int len = 0;while((len = fr.read(buf))!=-1){System.out.println(new String(buf,0,len));}//关闭流fr.close();}}

复制文件 从d盘到e盘

import java.io.*;public class IODemo5 {public static void main(String[] args) throws IOException{//copy_1();copy_2();}//用第一种读取方式public static void copy_1()throws IOException{//读取流FileReader fr = new FileReader("d:\\a.txt");//写入流FileWriter fw = new FileWriter("e:\\a.txt");char[] buf = new char[1024];int len =0;while((len = fr.read(buf))!= -1){//读fw.write(buf, 0, len);//写}//关闭流fr.close();fw.close();}//用第二种读取方式public static void copy_2()throws IOException{//读入流FileReader fr = new FileReader("d:\\a.txt");//写入流FileWriter fw = new FileWriter("e:\\b.txt");int len = 0;while((len = fr.read())!= -1){//读fw.write((char)len);//写}//关闭流fr.close();fw.close();}}

字符流的缓冲区

缓冲区的出现提高了对数据的读写效率

对应类

BufferedWriter  BufferedReader

缓冲区要结合流才可以使用

在流的基础上对流的功能进行了增强

示例代码:

<span style="font-size:18px;">import java.io.*;public class IOBufferedDemo {public static void main(String[] args)throws IOException {//创建一个写入流对象FileWriter fw = new FileWriter("d:\\buf.txt");        //为了提高字符写入流效率,加入了缓冲技术//只要将需要被提高效率的流对象作为参数传递给缓冲区的构造函数即可BufferedWriter bufw = new BufferedWriter(fw);for(int i = 1 ; i < 5; i++){bufw.write("abcd"+i);bufw.newLine();bufw.flush();}//记住,只要用到缓冲区,就要记得刷新//其实关闭缓冲区,就是在关闭缓冲区中的流对象bufw.close();}}</span>

字符读取流缓冲区

该缓冲区提供了一个一次读一行的方法,readLine,方便于对文本数据的获取。readLine方法返回的时候只返回回车符之前的数据内容,并不返回回车符。

当返回null时,表示读到文件末尾

示例代码:

<span style="font-size:18px;">import java.io.*;public class BufwDemo {public static void main(String[] args)throws IOException {//创建一个读取流对象和文件相关联FileReader fr = new FileReader("d:\\buf.txt");//为了提高效率,加入缓冲技术。将字符读取流对象作为参数传递给缓冲对象的构造函数BufferedReader bfr = new BufferedReader(fr);String line = null;//读取while((line = bfr.readLine()) != null){System.out.println(line);}//关闭流bfr.close();}}</span>

readLine方法的实现原理

import java.io.*;public class MyBufferedReader extends Reader {//传入一个Reader对象private Reader r;public MyBufferedReader(Reader r){this.r = r;}    //自己实现的readLine方法public String MyReadLine()throws IOException{int ch = 0;//定义一个StringBuilder来保存每行读到的数据StringBuilder sb = new StringBuilder();while((ch=(r.read()))!= -1){//如果读到换行 一字符串类型返回StringBuilder中存储的数据if(ch == '\r')continue;if(ch == '\n')return sb.toString();else//将每次读到的数据加入到StringBuilder中sb.append((char)ch);}if(sb.length() != 0)return sb.toString();return null;}    //实现父类抽象的close方法@Overridepublic void close() throws IOException {r.close();}    //实现父类的抽象read方法@Overridepublic int read(char[] cbuf, int off, int len) throws IOException {return r.read(cbuf, off, len);}<span style="font-size:18px;">}</span>

装饰设计模式:当想要对已有的对象进行功能增强时,可以定义类,将已有对象传入,基于已有的功能,并提供加强

功能。那么自定义的该类称为装饰类。装饰类通常会通过构造方法接受被装饰的对象。并基于被装饰的对象的功能,

提供更强的功能。

装饰模式比继承要更加灵活。避免了继承体系臃肿。而且降低了类与类之间的关系。装饰类因为增强已有对象具备的

能和已有的是相同的,只不过提供了更强功能。所以装饰类和被装饰类通常都是属于一个体系中的。

 

字节流BufferedInputStream的原理

import java.io.*;public class MyBufferedInputStream {//传入一个InputStreamprivate InputStream in;public MyBufferedInputStream(InputStream in) {this.in = in;}    //计数器private int count = 0;//指针private int pos = 0;byte[] buf = new byte[1024];public int myRead() throws IOException {if (count == 0) {if(count < 0)return -1;//用in的read方法读取数据 存储到数组buf中count = in.read(buf);//指针初始化pos = 0;//用byte b 记录数组buf中角标为pos的元素byte b = buf[pos];//计数器减一count--;//指针加一pos++;//返回b & 255return b & 255;}else if(count > 0){//用byte b 记录数组buf中角标为pos的元素byte b = buf[pos];//计数器减一count--;//指针加一pos++;//返回b & 255return b & 255;}return -1;}    //close方法public void myColse()throws IOException{in.close();}}

 

读取键盘录入的一行数据

System.out :对应的是标准输出设备,控制台

System.in: 对应的是标准输入设备,键盘

需求:

通过键盘录入数据

当录入一行数据后,就将该行数据进行打印

如果录入的数据是over,那么停止录入

import java.io.*;public class SysteminDemo {public static void main(String[] args)throws IOException {read();}public static void read()throws IOException{    //创建容器    StringBuilder sb = new StringBuilder();    //获取键盘读取流InputStream in = System.in;//定义变量记录读取到的字节,并循环获取int ch = 0;while(true){ch = in.read();//在存储之前需要判断是否是换行标记,因为换行标记不存储if(ch == '\r')continue;if(ch == '\n'){String str = sb.toString();if("over".equals(str))break;System.out.println(str.toUpperCase());sb.delete(0, sb.length());}else//将读取到的字节存储到StringBuilder中sb.append((char)ch);}}}

InputStreamReader是字节流向字符流转换的桥梁,它使用指定的charset读取字节并将其解码为字符,它使用的字符

集可以由名称指定或者显示给定

OutputStreamWriter是字符流通向字节流的桥梁:可使用指定的charset将要写入流中的字符编码成字节。它使用的字

符集可以由名称指定或显示给定,否则将接受平台默认的字符集

转换流 代码:

import java.io.*;public class ChangeDemo {public static void main(String[] args)throws IOException {print_3();}// 源为键盘,目的为控制台public static void print() throws IOException {// 读取缓冲流BufferedReader br = new BufferedReader(new InputStreamReader(System.in));// 写入缓冲流BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));String line = null;// 读写while ((line = br.readLine()) != null) {if("over".equals(line))break;bw.write(line);bw.newLine();bw.flush();}// 关闭流br.close();bw.close();}// 源为文件,目的为控制台public static void print_2() throws IOException {//读取缓冲流        BufferedReader br = new BufferedReader(        new InputStreamReader(new FileInputStream("d:\\a.txt")));// 写入缓冲流BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));String line = null;// 读写while ((line = br.readLine()) != null) {bw.write(line);bw.newLine();bw.flush();}//关闭流br.close();bw.close();}//源为键盘,目的为文件public static void print_3()throws IOException{//读取缓冲流BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//写入缓冲流BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("e:\\b.txt")));String line = null;// 读写while ((line = br.readLine()) != null) {if("over".equals(line))break;bw.write(line);bw.newLine();bw.flush();}//关闭流br.close();bw.close();}}

 

异常日志:

import java.io.*;import java.util.*;import java.text.*;public class ExceptionInfo {public static void main(String[] args) {try{int[] arr = new int[2];System.out.println(arr[2]);}catch(Exception e){try{//建立PrintStream流PrintStream ps = new PrintStream("d:\\Exception.log");//获得当前时间对象Date d = new Date();//格式化时间对象SimpleDateFormat sdf =new  SimpleDateFormat("yy-MM-dd HH:mm:ss");String str =sdf.format(d);//将格式化后的时间写入日志文件ps.println(str);//将异常写入日志文件e.printStackTrace(ps);}catch(IOException ex){throw new RuntimeException("日志文件创建失败");}}}}


 

 

 


 

 

 


 


 


 

 

0 0