黑马程序员_IO流(一)

---------------------- ASP.Net+Unity开发.Net培训、期待与您交流! --------------------



IO流(概述)
      字节流抽象基类:InputStream   OutputStream
    字符流抽象基类:Reader   Writer
IO流(FileWriter)
     FileWriter:操作文件,写入。后缀名:父类名,前缀名:功能

public class FileWriterDemo {

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

		//创建一个FileWriter对象,该对象一被初始化就必须要明确被操作的文件
		//该文件会被创建到指定目录下,如果该目录下已有同名文件,将被覆盖
		//该步就是在明确数据要存放的目的地
		FileWriter fw = new FileWriter("demo.txt");
		
		//调用writer方法,将字符串写到流中
		fw.write("gg");
		
		//刷新流对象中缓存中的数据,将数据刷新到目的地中
		fw.flush();
		
		//关闭流资源,关闭前会刷新一次,刷新后流会关闭,不能继续使用。
		fw.close();
	}
}


IO流(IO异常处理方式)

public class FileWriterDemo2 {

	public static void main(String[] args) {

		FileWriter fw = null;
		try
		{
			fw = new FileWriter("demo.txt");
			fw.write("abcde");
		}
		catch(IOException e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			try
			{
				if(fw!=null)
					fw.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}
		}
	}
}


IO流(文件的续写)

public class FileWriterDemo3 {

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

		//传递一个true参数,代表不覆盖已有的文件,并在文件末尾出续写
		FileWriter fw = new FileWriter("Demo.txt",true);
		
		fw.write("hello\r\nhi");
		
		fw.close();
	}
}


IO流(文本文件读取方式一)

public class FileReaderDemo {

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

		//创建一个文件读取流对象,和指定名称的文件相关联
		//要保证该文件是已经存在的,如果不存在,会发生异常 FileNotFoundException
		FileReader fr = new FileReader("Demo.txt");
		
		//调用读取流对象的read方法
		//read() : 一次读一个字符,而且自动往下读。
		
		int ch = 0;
		while((ch=fr.read())!=-1)
		{
			System.out.print((char)ch);
		}
		/*
		while(true)
		{
			int ch = fr.read();
			if(ch==-1)
				break;
			System.out.print((char)ch);
		}
		*/
	}
}


IO流(文本文件读取方式二)

public class FileReaderDemo2 {

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

		FileReader fr = new FileReader("Demo.txt");
		
		//定义一个字符数组,用于存储读到的字符
		//该read(char[])返回的是读到的字符个数
		char[] buf = new char[1024];
		int num = 0;
		while((num=fr.read(buf))!=-1)
		{
			System.out.println(new String(buf,0,num));
		}
		fr.close();
	}
}


IO流(文本文件读取练习)

//读取一个.java文件并打印

public class FileReaderTest {

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

		FileReader fr = new FileReader("Test.java");
			
		char[] buf = new char[1024];
		int num = 0;
			
		while((num=fr.read(buf))!=-1)
		{
			System.out.print(new String(buf,0,num));
		}
		
		fr.close();
	}
}


IO流(拷贝文本文件)
/*
复制一个文本文件

复制原理:
就是将一个文件数据存储到另一个文件中

步骤:
1.创建一个文件,用于存储另一个文件中的数据
2.定义读取流和文件文件关联
3.通过不断读写完成数据存储
4.关闭资源
*/

public class CopyText {

	public static void copy()
	{
		FileReader fr = null;
		FileWriter fw = null;
		try
		{
			fr = new FileReader("Hello.txt");
			fw = new FileWriter("Hello_Copy.txt");
			
			char[] buf = new char[1024];
			int len = 0;
			
			while((len=fr.read(buf))!=-1)
			{
				fw.write(buf,0,len);
			}
		}
		catch(IOException e)
		{
			throw new RuntimeException("读写失败");
		}
		finally
		{
			if(fr!=null)
				try
				{
					fr.close();
				}
				catch(IOException e)
				{
				}
			if(fw!=null)
				try
				{
					fw.close();
				}
				catch(IOException e)
				{
				}
		}
	}
	/*
	public static void copy2() throws IOException
	{
		FileReader fr = new FileReader("Hi.txt");
		FileWriter fw = new FileWriter("Hi_Copy.txt");
		
		int ch = 0;
		
		while((ch=fr.read())!=-1)
		{
			fw.write(ch);
		}
		fr.close();
		fw.close();
	}
	*/
	public static void main(String[] args) //throws IOException 
	{
		copy();
		//copy2();
	}
}

BufferedWriter
     字符流缓冲区
    缓冲区是为了提高流的效率,创建缓冲区,必须先有流对象
    缓冲区中提供了跨平台的换行符  newLine();

public class BufferedWriterDemo {

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

		//创建一个字符写入流对象
		FileWriter fw = new FileWriter("buf.txt");
		
		//加入缓冲技术,只需将流对象作为参数传递给缓冲区的构造函数
		BufferedWriter bufw = new BufferedWriter(fw);
		
		for(int x=0; x<5; x++)
		{
			bufw.write("gg"+x);
			bufw.newLine();
			bufw.flush();
		}
		bufw.close();
	}
}

BufferedReader

     该缓冲区提供一个一次读一行的方法  readLine();
    返回null时,表示读到文件末尾

public class BufferedReaderDemo {

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

		//创建读取流对象和文件关联
		FileReader fr = new FileReader("buf.txt");
		
		//加入缓冲技术,将字符流对象作为参数传递给缓冲区的构造函数
		BufferedReader bufr = new BufferedReader(fr);
		
		String line = null;
		
		while((line=bufr.readLine())!=null)
		{
			System.out.println(line);
		}
		bufr.close();
	}
}

通过缓冲区复制文本文件

public class CopyTextByBuf {

	public static void main(String[] args) {

		BufferedReader bufr = null;
		BufferedWriter bufw = null;
		
		try
		{
			bufr = new BufferedReader(new FileReader("buf.txt"));
			bufw = new BufferedWriter(new FileWriter("buf_copy.txt"));
			
			String line = null;
			
			while((line=bufr.readLine())!=null)
			{
				bufw.write(line);
				bufw.newLine();
				bufw.flush();
			}
		}
		catch(IOException e)
		{
			throw new RuntimeException("读写失败");
		}
		finally
		{
			try
			{
				if(bufr!=null)
					bufr.close();
			}
			catch(IOException e)
			{
				throw new RuntimeException("读取关闭失败");
			}
			try
			{
				if(bufw!=null)
					bufw.close();
			}
			catch(IOException e)
			{
				throw new RuntimeException("写入关闭失败");
			}
		}
	}
}

readLine的原理图例

     最终使用的是read方法,一次读一个 

class MyBufferedReader
{
	private FileReader r;
	MyBufferedReader(FileReader r)
	{
		this.r = r;
	}
	
	//可以一次读一行的方法
	public String myReadLine() throws IOException
	{
		//定义一个临时容器,原BufferedReader封装的是字符数组
		//定义一个StringBuilder容器
		StringBuilder sb = new StringBuilder();
		int ch = 0;
		while((ch=r.read())!=-1)
		{
			if(ch=='\r')
				continue;
			if(ch=='\n')
				return sb.toString();
			else
				sb.append((char)ch);
		}
		if(sb.length()!=0)
			return sb.toString();
		return null;
	}
	public void myClose() throws IOException
	{
		r.close();
	}
}
public class MyBufferedReaderDemo {

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

		FileReader fr = new FileReader("buf.txt");
		MyBufferedReader myBuf = new MyBufferedReader(fr);
		String line = null;
		while((line=myBuf.myReadLine())!=null)
		{
			System.out.println(line);
		}
		myBuf.myClose();
	}
}

装饰设计模式

     装饰设计模式:当想要对已有的对象进行功能增强时,可以定义类,将已有对象传入,基于已有的功能,并提供加强功能,那么自定义的类称为装饰类。
    装饰类通常会通过构造方法接收被装饰的对象,并基于被装饰的对象的功能,提供更强的功能。

//装饰设计模式

class Person
{
	public void chifan()
	{
		System.out.println("吃饭");
	}
}
class SuperPerson
{
	private Person p;
	SuperPerson(Person p)
	{
		this.p = p;
	}
	public void superChifan()
	{
		System.out.println("开胃酒");
		p.chifan();
		System.out.println("甜点");
	}
}
public class PersonDemo {

	public static void main(String[] args) {

		Person p = new Person();
		//p.chifan();
		SuperPerson sp = new SuperPerson(p);
		sp.superChifan();
	}
}

装饰和继承的区别

     装饰模式比继承灵活,避免了继承体系的臃肿,而且降低了类与类之间的关系。
    装饰类因为是增强已有对象,具备的功能和已有对象是相同的,所以装饰类和被装饰类通常都是属于一个体系。

自定义装饰类

class MyBufferedReader extends Reader
{
	private Reader r;
	MyBufferedReader(Reader r)
	{
		this.r = r;
	}
	
	//可以一次读一行的方法
	public String myReadLine() throws IOException
	{
		//定义一个临时容器,原BufferedReader封装的是字符数组
		//定义一个StringBuilder容器
		StringBuilder sb = new StringBuilder();
		int ch = 0;
		while((ch=r.read())!=-1)
		{
			if(ch=='\r')
				continue;
			if(ch=='\n')
				return sb.toString();
			else
				sb.append((char)ch);
		}
		if(sb.length()!=0)
			return sb.toString();
		return null;
	}
	/*
	覆盖Reader类中的抽象方法
	*/
	public int read(char[] cbuf, int off, int len) throws IOException
	{
		return r.read(cbuf,off,len);
	}
	public void close() throws IOException
	{
		r.close();
	}
	public void myClose() throws IOException
	{
		r.close();
	}
}
public class MyBufferedReaderDemo {

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

		FileReader fr = new FileReader("buf.txt");
		MyBufferedReader myBuf = new MyBufferedReader(fr);
		String line = null;
		while((line=myBuf.myReadLine())!=null)
		{
			System.out.println(line);
		}
		myBuf.myClose();
	}
}

LineNumberReader

public class LineNumberReaderDemo {

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

		FileReader fr = new FileReader("buf.txt");
		
		LineNumberReader lnr = new LineNumberReader(fr);
		
		String line = null;
		lnr.setLineNumber(100);
		while((line=lnr.readLine())!=null)
		{
			System.out.println(lnr.getLineNumber()+":"+line);
		}
		lnr.close();
	}
}

MyLineNumberReader

class MyLineNumberReader
{
	private Reader r;
	private int lineNumber;
	MyLineNumberReader(Reader r)
	{
		this.r = r;
	}
	public String myReadLine() throws IOException
	{
		lineNumber++;
		StringBuilder sb = new StringBuilder();
		int ch = 0;
		while((ch=r.read())!=-1)
		{
			if(ch=='\r')
				continue;
			if(ch=='\n')
				return sb.toString();
			else
				sb.append((char)ch);
		}
		if(sb.length()!=0)
			return sb.toString();
		return null;
	}
	public void setLineNumber(int lineNumber)
	{
		this.lineNumber = lineNumber;
	}
	public int getLineNumber()
	{
		return lineNumber;
	}
	public void myClose() throws IOException
	{
		r.close();
	}
}
public class MyLineNumberReaderDemo {

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

		FileReader fr = new FileReader("buf.txt");
		MyLineNumberReader mylnr = new MyLineNumberReader(fr);
		
		mylnr.setLineNumber(5);
		String line = null;
		while((line=mylnr.myReadLine())!=null)
		{
			System.out.println(mylnr.getLineNumber()+":"+line);
		}
		mylnr.myClose();
	}
}


字节流File读写操作

public class FileStream {

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

		writeFile();
		readFile_1();
		readFile_2();
		readFile_3();
	}
	
	public static void writeFile() throws IOException
	{
		FileOutputStream fos = new FileOutputStream("fos.txt");
		
		fos.write("abcde".getBytes());
		fos.close();
	}
	
	public static void readFile_1() throws IOException
	{
		FileInputStream fis = new FileInputStream("fos.txt");
		
		int ch = 0;
		while((ch=fis.read())!=-1)
		{
			System.out.println((char)ch);
		}
		fis.close();
	}
	
	public static void readFile_2() throws IOException
	{
		FileInputStream fis = new FileInputStream("fos.txt");
		
		byte[] buf = new byte[1024];
		int len = 0;
		while((len=fis.read(buf))!=-1)
		{
			System.out.println(new String(buf,0,len));
		}
		fis.close();
	}
	
	public static void readFile_3() throws IOException
	{
		FileInputStream fis = new FileInputStream("fos.txt");
		
		//定义一个刚好的缓冲区,不用循环。
		byte[] buf = new byte[fis.available()];
		
		fis.read(buf);
		System.out.println(new String(buf));
		fis.close();
	}
}

拷贝图片

/*
复制一个图片
思路:
1.用字节读取流对象和图片关联
2.用字节写入流对象创建一个图片文件,用于存储获取到的图片数据
3.通过循环读写,完成数据的存储
4.关闭资源
*/

public class CopyPic {

	public static void main(String[] args) {

		FileInputStream fis = null;
		FileOutputStream fos = null;
		try
		{
			fis = new FileInputStream("Ruler.jpg");
			fos = new FileOutputStream("Ruler_copy.jpg");
			byte[] buf = new byte[1024];
			int len = 0;
			while((len=fis.read(buf))!=-1)
			{
				fos.write(buf,0,len);
			}
		}
		catch(IOException e)
		{
			throw new RuntimeException("复制文件失败");
		}
		finally
		{
			try
			{
				if(fis!=null)
					fis.close();
			}
			catch(IOException e)
			{
				throw new RuntimeException("读取文件失败");
			}
			try
			{
				if(fos!=null)
					fos.close();
			}
			catch(IOException e)
			{
				throw new RuntimeException("写入文件失败");
			}
		}
	}
}

字节流的缓冲区   自定义字节流的缓冲区-read和write的特点

CopyMp3

public class CopyMp3 {

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

		long start = System.currentTimeMillis();
		copy_1();
		long end = System.currentTimeMillis();
		System.out.println((end-start)+"毫秒");
		long start2 = System.currentTimeMillis();
		copy_2();
		long end2 = System.currentTimeMillis();
		System.out.println((end2-start2)+"毫秒");
	}
	
	public static void copy_1() throws IOException
	{
		BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("V3.mp3"));
		BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("V3_copy.mp3"));
		
		int by = 0;
		while((by=bufis.read())!=-1)
		{
			bufos.write(by);
		}
		bufis.close();
		bufos.close();
	}
	public static void copy_2() throws IOException
	{
		MyBufferedInputStream bufis = new MyBufferedInputStream(new FileInputStream("V3.mp3"));
		BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("V3_copy2.mp3"));
		
		int by = 0;
		while((by=bufis.myRead())!=-1)
		{
			bufos.write(by);
		}
		bufis.myClose();
		bufos.close();
	}
}

      MyBufferedInputStream
public class MyBufferedInputStream {

	private InputStream in;
	private byte[] buf = new byte[1024];
	private int pos = 0, count = 0;
	
	MyBufferedInputStream(InputStream in)
	{
		this.in = in;
	}
	//一次读一个字节,从缓冲区(字节数组)获取
	public int myRead() throws IOException
	{
		//通过in读取硬盘上的数据,并存储buf冲
		if(count==0)
		{
			count = in.read(buf);
			if(count<0)
				return -1;
			pos = 0;
			byte b = buf[pos];
			
			count--;
			pos++;
			return b&255;
		}
		else if(count>0)
		{
			byte b = buf[pos];
			count--;
			pos++;
			return b&255;
		}
		return -1;
	}
	public void myClose() throws IOException
	{
		in.close();
	}
}

读取键盘录入

/*
通过键盘录入数据
当录入一行数据后,就将改行数据进行打印
当录入over,就停止录入
*/

public class ReadIn {

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

		InputStream in = System.in;
		StringBuilder sb = new StringBuilder();
		while(true)
		{
			int 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);
		}
	}
}

读取转换流     写入转换流

/*
用readLine方法完成键盘录入的一行数据的读取
readLine方法是字符流BufferedReader类中的方法
而键盘录入的read方法是字节流InputStream的方法
通过读取转换流将字节流转换成字符流再使用字符流缓冲区的readLine方法
*/

public class TransStreamDemo {

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

		//获取键盘录入对象
		//InputStream in = System.in;
		//将字节流转换成字符流对象
		//InputStreamReader isr = new InputStreamReader(in);
		//为了提高效率,将字符串进行缓冲区技术高效操作。使用BufferedReader
		//BufferedReader bufr = new BufferedReader(isr);
		
		//键盘录入最常见写法
		BufferedReader bufr =
				new BufferedReader(new InputStreamReader(System.in));
		
		//OutputStream out = System.out;
		//OutputStreamWriter osw = new OutputStreamWriter(out);
		//BufferedWriter bufw = new BufferedWriter(osw);
		
		BufferedWriter bufw =
				new BufferedWriter(new OutputStreamWriter(System.out));
		
		String line = null;
		while((line=bufr.readLine())!=null)
		{
			if("over".equals(line))
				break;
			bufw.write(line.toUpperCase());
			bufw.newLine();
			bufw.flush();
		}
		bufr.close();
	}
}

流操作规律-1    流操作规律-2

      流操作的基本规律
    1.明确源和目的
         源:输入流。InputStream  Reader
         目的:输出流。OutputStream  Writer
    2.操作的数据是否纯文本
         是:字符流
         不是:字节流
    3.当体系明确后,再明确要使用哪个具体对象
         通过设备来进行区分
              源设备:内存、硬盘、键盘
              目的设备:内存、硬盘、控制台


public class TransStreamDemo2 {

	public static void main(String[] args) throws IOException {
		
		//键盘录入最常见写法
		//源:键盘。目的:控制台
		BufferedReader bufr =
				new BufferedReader(new InputStreamReader(System.in));
		
		BufferedWriter bufw =
				new BufferedWriter(new OutputStreamWriter(System.out));
		
		//源:键盘。目的:文件
		//BufferedReader bufr =
				//new BufferedReader(new InputStreamReader(System.in));
		
		//BufferedWriter bufw =
				//new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out.txt)));
		
		//源:文件。目的:控制台
		//BufferedReader bufr =
				//new BufferedReader(new InputStreamReader(new FileInputStream(in.txt)));

		//BufferedWriter bufw =
				//new BufferedWriter(new OutputStreamWriter(System.out));
		
		String line = null;
		while((line=bufr.readLine())!=null)
		{
			if("over".equals(line))
				break;
			bufw.write(line.toUpperCase());
			bufw.newLine();
			bufw.flush();
		}
		bufr.close();
	}
}

异常的日志信息

public class ExceptionInfo {

	public static void main(String[] args) {

		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("exception.log");
				ps.println(d.toString());
				System.setOut(ps);
			}
			catch(IOException ex)
			{
				throw new RuntimeException("日志文件创建失败");
			}
			e.printStackTrace(System.out);
		}
	}
}

系统信息

public class SystemInfo {

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

		Properties prop = System.getProperties();
		prop.list(new PrintStream("sysinfo.txt"));
	}
}





----------------------ASP.Net+Unity开发.Net培训、期待与您交流! --------------------

详细请查看:http://edu.csdn.net






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值