Java I/O层次结构详解

今天总结一下Java I/O文件读写基本类相关知识和概念,对于程序设计者来说,创建一个好的输入/输出系统是一项艰难的任务,其中挑战来源于所有的可能性,不仅存在各种源端与接收端(文件,控制台,网络链接等),而且还需要以各种不同的方式与它们通信(顺序,随机存取,缓冲,二进制,按字符,按行,按字等)。

 

Java I/O主要包括如下几个层次:

1. File(文件特征与管理):用于文件或者目录的描述信息,例如生成新目录,修改文件名,删除文件,判断文件所在路径等。

2. InputStream(二进制格式操作):抽象类,基于字节的输入操作,是所有输入流的父类。定义了所有输入流都具有的共同特征。

3. OutputStream(二进制格式操作):抽象类。基于字节的输出操作。是所有输出流的父类。定义了所有输出流都具有的共同特征。

 

Java中字符是采用Unicode标准,一个字符是16位,即一个字符使用两个字节来表示。为此,JAVA中引入了处理字符的流。

4. Reader(文件格式操作):抽象类,基于字符的输入操作。

5. Writer(文件格式操作):抽象类,基于字符的输出操作。

6. RandomAccessFile(随机文件操作):它的功能丰富,可以从文件的任意位置进行存取(输入输出)操作

 

1. File

它是独立于系统平台的,利用其构造函数创建出相应的File 对象;再调用其中的方法实现对文件的各个属性方面的操作。

构造函数:
File( String  path)
File(String path, String FileName)
File(File dir, String name)

 

用途:File类提供了一种与机器无关的方式来描述一个文件对象的属性,通过类File所提供的方法,可以得到文件或目录的描述信息,这主要包括名称、所在路经、可读性、可写性、文件的长度等,还可以生成新的目录、改变文件名、删除文件、列出一个目录中所有的文件等。 

public static void main(String[] args) throws IOException {
		File f = new File("dir");

		f.createNewFile();// 创建一个.txt这个文件

		f.mkdir();// 创建一个名为.txt的目录

		/*
		 * 使用绝对路径
		 * 
		 * File f=new File("D:\\dir\\src\\A.java");
		 * 
		 * f.createNewFile();
		 */

		/*
		 * 跨平台使用
		 * 
		 * 根据不同操作系统获得对应的分隔符 File fDir=new File(File.separator);
		 * 
		 * String strFile="dir"+File.separator+"src"+File.separator +"A.java";
		 * 
		 * File f=new File(fDir,strFile);
		 * 
		 * f.createNewFile();
		 * 
		 * f.delete();//删除文件或目录
		 * 
		 * //f.deleteOnExit();
		 */

		/*
		 * 在缺省的临时文件目录下创建临时文件
		 * 
		 * for(int i=0;i<5;i++)
		 * 
		 * {
		 * 
		 * File f=File.createTempFile("winTemp",".tmp");
		 * 
		 * f.deleteOnExit();//退出时删除
		 * 
		 * 
		 * 
		 * }
		 */

		/*
		 * 列出指定目录下所有子目录及文件的名称
		 */
		File fDir = new File(File.separator);
		String strFile = "dir" + File.separator + "src";
		File f = new File(fDir, strFile);
		String[] names = f.list();
		for (int i = 0; i < names.length; i++) {
			System.out.println(names[i]);
		}

		// 有过滤器的情况FilenameFilter是个接口
		File dir = new File(File.separator);

		String filepath = "dir" + File.separator + "src";

		/**
		 * dir
		 * 上级抽象路径,如果dir为null,那么程序将自动调用单个参数的File构造方法,同时将filepath路径应用到File但构造参数
		 * 如果dir为//,则此路径为本文件所在磁盘根目录
		 */
		File f = new File(dir, filepath);
		if (f.exists()) {
		} else {
			f.mkdirs();
		}

		String[] names = f.list(new FilenameFilter() { // 实现了FilenameFilter接口的匿名类,实现accept方法过滤文件

					@Override
					public boolean accept(File dir, String name) {
						System.out.println(name.indexOf(".java"));
						return name.indexOf(".java") != -1;
					}
				});

		for (int i = 0; i < names.length; i++) {
			System.out.println(names[i]);
		}
	}

 

2. InputStream/OutputStream(抽象基类)

(1) 它们主要提供文件内容操作的基本功能函数read()、 write()、close()等;一般都是创建出其派生类对象(完成指定的特殊功能)来实现文件读写。
(2)文件操作的一般方法:
根据所要操作的类型生成对应输入输出文件类的对象;
调用此类的成员函数实现文件数据的读写;
关闭此文件流对象。
(3)文件操作的应用要点:
异常的捕获:由于包java.io中几乎所有的类都声明有I/O异常,因此程序应该对这些异常加以处理。
流结束的判断:方法read()的返回值为-1时;readLine()的返回值为null时。

 

上边两个抽象基类实现类有FileInputStream/FileOutputStream(本地文件读写类):它们用于本地文件的二进制格式顺序读写。

 

java.io.FileInputStream是InputStream的子类。从开头File名称上就可以知道,FileInputStream与从指定的文件中读取数据至目的地有关。而java.io.FileOutputStream是OutputStream的子类,顾名思义,FileOutputStream主要与从来源地写入数据至指定的文件中有关。

 

当建立一个FileInputStream或FileOutputStream的实例时,必须指定文件位置及文件名称,实例被建立时文件的流就会开启;而不使用流时,必须关闭文件流,以释放与流相依的系统资源,完成文件读/写的动作。

 

FileInputStream可以使用read()方法一次读入一个字节,并以int类型返回,或者是使用read()方法时读入至一个byte数组,byte数组的元素有多少个,就读入多少个字节。在将整个文件读取完成或写入完毕的过程中,这么一个byte数组通常被当作缓冲区,因为这么一个byte数组通常扮演承接数据的中间角色。

public class FileStreamDemo {
	
	public static void main(String[] args) {
		
		try {
			
			byte[] buffer = new byte[1024];
			
			// 来源文件
			FileInputStream fileInputStream = new FileInputStream(new File(args[0]));
			
			// 目的文件
			FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1]));
			
			// available()可取得未读取的数据长度
			System.out.println("复制文件:" + fileInputStream.available() + "字节");

			while (true) {
				if (fileInputStream.available() < 1024) {
					// 剩余的数据比1024字节少
					// 一位一位读出再写入目的文件
					int remain = -1;
					while ((remain = fileInputStream.read()) != -1) {
						fileOutputStream.write(remain);
					}
					break;
				} else {
					// 从来源文件读取数据至缓冲区
					fileInputStream.read(buffer);
					// 将数组数据写入目的文件
					fileOutputStream.write(buffer);
				}
			}

			// 关闭流
			fileInputStream.close();
			fileOutputStream.close();

			System.out.println("复制完成");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("using: java FileStreamDemo src des");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

 PipedInputStream/PipedOutputStream(管道输入输出)

(1)它用于实现管道的二进制格式的输入输出(将一个线程的输出结果直接连接到另一个线程的输入端口,实现两者数据直接传送)。
(2) PipedReader/PipedWriter类:它用于实现管道的字符格式的输入输出。
(3)要求:操作时需要将两个端口相互连结。
(4)实现原理:

(5) 管道的连接:
方法一:是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象

方法二:是利用双方类中的任一个成员函数 connect()相连接
(6)实例讲解: Sender.java, Receiver.java, PipedIO.java (使用PipedWriter,PipedReader)

Sender.java

import java.io.PipedWriter;
import java.util.Random;

class Sender extends Thread {
	private Random rand = new Random();
	private PipedWriter out = new PipedWriter();

	public PipedWriter getPipedWriter() {
		return out;
	}

	public void run() {
		while (true) {
			for (char c = 'A'; c <= 'z'; c++) {
				try {
					out.write(c);
					sleep(rand.nextInt(500));
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
}

 

 

Receiver.java

import java.io.IOException;
import java.io.PipedReader;

class Receiver extends Thread {
	private PipedReader in;

	public Receiver(Sender sender) throws IOException {
		in = new PipedReader(sender.getPipedWriter());
	}

	public void run() {
		try {
			while (true) {
				// Blocks until characters are there:
				System.out.println("Read: " + (char) in.read());
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}

 

PipedIO.java

public class PipedIO {
	
	public static void main(String[] args) throws Exception {
		Sender sender = new Sender();
		Receiver receiver = new Receiver(sender);
		sender.start();
		receiver.start();
	}
}

 

(7)实例讲解: Sender1.java, Receiver1.java, PipedIO1.java (使用

PipedInputStream,PipedOutputStream)

 

Sender1.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PipedOutputStream;

public class Sender1 extends Thread {

	private PipedOutputStream pos;
	
	private File file;

	// 构造方法
	Sender1(PipedOutputStream pos, String fileName) {
		this.pos = pos;
		file = new File(fileName);
	}

	// 线程运行方法
	public void run() {
		try {
			// 读文件内容
			FileInputStream fs = new FileInputStream(file);
			int data;
			while ((data = fs.read()) != -1) {
				// 写入管道始端
				pos.write(data);
			}
			pos.close();
		} catch (IOException e) {
			System.out.println("Sender Error" + e);
		}
	}
}

 

Receiver1.java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;

public class Receiver1 extends Thread {

	private PipedInputStream pis;
	private File file;

	// 构造方法
	Receiver1(PipedInputStream pis, String fileName) {
		this.pis = pis;
		file = new File(fileName);
	}

	// 线程运行
	public void run() {
		try {
			// 写文件流对象
			FileOutputStream fs = new FileOutputStream(file);
			int data;
			// 从管道末端读
			while ((data = pis.read()) != -1) {
				// 写入本地文件
				fs.write(data);
			}
			pis.close();
		} catch (IOException e) {
			System.out.println("Receiver Error" + e);
		}
	}
}

 

PipedIO1.java

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedIO1 {

	public static void main(String[] args) {
		try {
			// 构造读写的管道流对象
			PipedInputStream pis = new PipedInputStream();
			PipedOutputStream pos = new PipedOutputStream();
			
			// 实现关联
			pos.connect(pis);
			
			// 构造两个线程,并且启动。
			new Sender1(pos, "c:\\a1.txt").start();
			new Receiver1(pis, "c:\\a2.txt").start();
		} catch (IOException e) {
			System.out.println("Pipe Error" + e);
		}
	}
}

 

 

RandomAccessFile(随机文件读写类):

(1)RandomAccessFile类:它直接继承于Object类而非InputStream/OutputStream类,从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。

(2)由于RandomAccessFile类实现了DataOutput与DataInput接口,因而利用它可以读写Java中的不同类型的基本类型数据(比如采用readLong()方法读取长整数,而利用readInt()方法可以读出整数值等)。

 

RandomFileRW.java

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomFileRW {

	public static void main(String args[]) {
		StringBuffer buf = new StringBuffer();
		char ch;
		
		try {
			while ((ch = (char) System.in.read()) != '\n') {
				buf.append(ch);
			}
			
			// 读写方式可以为"r" or "rw"
			
			/**
			 * @param mode 1. r 2. rw 3. rws 4. rwd
			 * "r" Open for reading only. Invoking any of the write methods of the resulting object will
			 *  	cause an IOException to be thrown.  
			 * "rw" Open for reading and writing. If the file does not already exist then an attempt will
			 *  	be made to create it.  
			 * "rws" Open for reading and writing, as with "rw", and also require that every update to the
			 *  	file's content or metadata be written synchronously to the underlying storage device.  
			 * "rwd"   Open for reading and writing, as with "rw", and also require that every update to the
			 *  	file's content be written synchronously to the underlying storage device. 
			 */
			RandomAccessFile myFileStream = new RandomAccessFile("c:\\UserInput.txt", "rw");
			myFileStream.seek(myFileStream.length());
			myFileStream.writeBytes(buf.toString());
			
			// 将用户从键盘输入的内容添加到文件的尾部
			myFileStream.close();
		} catch (IOException e) {
		}
	}
}

 

InputStream.java

 

OutputStream.java

 

FilterInputStream.java

 

FilterOutputStream.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值