(Java基础知识) Java/IO 流详解

无情 阅读:676 2021-04-01 10:17:28 评论:0
总结一下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所提供的方法,可以得到文件或目录的描述信息,这主要包括名称、所在路经、可读性、可写性、文件的长度等,还可以生成新的目录、改变文件名、删除文件、列出一个目录中所有的文件等。 

Java代码   收藏代码
  1. public static void main(String[] args) throws IOException {  
  2.         File f = new File("dir");  
  3.   
  4.         f.createNewFile();// 创建一个.txt这个文件  
  5.   
  6.         f.mkdir();// 创建一个名为.txt的目录  
  7.   
  8.         /* 
  9.          * 使用绝对路径 
  10.          *  
  11.          * File f=new File("D:\\dir\\src\\A.java"); 
  12.          *  
  13.          * f.createNewFile(); 
  14.          */  
  15.   
  16.         /* 
  17.          * 跨平台使用 
  18.          *  
  19.          * 根据不同操作系统获得对应的分隔符 File fDir=new File(File.separator); 
  20.          *  
  21.          * String strFile="dir"+File.separator+"src"+File.separator +"A.java"; 
  22.          *  
  23.          * File f=new File(fDir,strFile); 
  24.          *  
  25.          * f.createNewFile(); 
  26.          *  
  27.          * f.delete();//删除文件或目录 
  28.          *  
  29.          * //f.deleteOnExit(); 
  30.          */  
  31.   
  32.         /* 
  33.          * 在缺省的临时文件目录下创建临时文件 
  34.          *  
  35.          * for(int i=0;i<5;i++) 
  36.          *  
  37.          * {  
  38.          *  
  39.          * File f=File.createTempFile("winTemp",".tmp"); 
  40.          *  
  41.          * f.deleteOnExit();//退出时删除 
  42.          *  
  43.          *  
  44.          *  
  45.          * } 
  46.          */  
  47.   
  48.         /*  
  49.          * 列出指定目录下所有子目录及文件的名称  
  50.          */  
  51.         File fDir = new File(File.separator);  
  52.         String strFile = "dir" + File.separator + "src";  
  53.         File f = new File(fDir, strFile);  
  54.         String[] names = f.list();  
  55.         for (int i = 0; i < names.length; i++) {  
  56.             System.out.println(names[i]);  
  57.         }  
  58.   
  59.         // 有过滤器的情况FilenameFilter是个接口  
  60.         File dir = new File(File.separator);  
  61.   
  62.         String filepath = "dir" + File.separator + "src";  
  63.   
  64.         /** 
  65.          * dir 
  66.          * 上级抽象路径,如果dir为null,那么程序将自动调用单个参数的File构造方法,同时将filepath路径应用到File但构造参数 
  67.          * 如果dir为//,则此路径为本文件所在磁盘根目录 
  68.          */  
  69.         File f = new File(dir, filepath);  
  70.         if (f.exists()) {  
  71.         } else {  
  72.             f.mkdirs();  
  73.         }  
  74.   
  75.         String[] names = f.list(new FilenameFilter() { // 实现了FilenameFilter接口的匿名类,实现accept方法过滤文件  
  76.   
  77.                     @Override  
  78.                     public boolean accept(File dir, String name) {  
  79.                         System.out.println(name.indexOf(".java"));  
  80.                         return name.indexOf(".java") != -1;  
  81.                     }  
  82.                 });  
  83.   
  84.         for (int i = 0; i < names.length; i++) {  
  85.             System.out.println(names[i]);  
  86.         }  
  87.     }  
  1. public static void main(String[] args) throws IOException {  
  2.         File f = new File("dir");  
  3.   
  4.         f.createNewFile();// 创建一个.txt这个文件   
  5.   
  6.         f.mkdir();// 创建一个名为.txt的目录   
  7.   
  8.         /* 
  9.          * 使用绝对路径 
  10.          *  
  11.          * File f=new File("D:\\dir\\src\\A.java"); 
  12.          *  
  13.          * f.createNewFile(); 
  14.          */  
  15.   
  16.         /* 
  17.          * 跨平台使用 
  18.          *  
  19.          * 根据不同操作系统获得对应的分隔符 File fDir=new File(File.separator); 
  20.          *  
  21.          * String strFile="dir"+File.separator+"src"+File.separator +"A.java"; 
  22.          *  
  23.          * File f=new File(fDir,strFile); 
  24.          *  
  25.          * f.createNewFile(); 
  26.          *  
  27.          * f.delete();//删除文件或目录 
  28.          *  
  29.          * //f.deleteOnExit(); 
  30.          */  
  31.   
  32.         /* 
  33.          * 在缺省的临时文件目录下创建临时文件 
  34.          *  
  35.          * for(int i=0;i<5;i++) 
  36.          *  
  37.          * {  
  38.          *  
  39.          * File f=File.createTempFile("winTemp",".tmp"); 
  40.          *  
  41.          * f.deleteOnExit();//退出时删除 
  42.          *  
  43.          *  
  44.          *  
  45.          * } 
  46.          */  
  47.   
  48.         /* 
  49.          * 列出指定目录下所有子目录及文件的名称 
  50.          */  
  51.         File fDir = new File(File.separator);  
  52.         String strFile = "dir" + File.separator + "src";  
  53.         File f = new File(fDir, strFile);  
  54.         String[] names = f.list();  
  55.         for (int i = 0; i < names.length; i++) {  
  56.             System.out.println(names[i]);  
  57.         }  
  58.   
  59.         // 有过滤器的情况FilenameFilter是个接口   
  60.         File dir = new File(File.separator);  
  61.   
  62.         String filepath = "dir" + File.separator + "src";  
  63.   
  64.         /** 
  65.          * dir 
  66.          * 上级抽象路径,如果dir为null,那么程序将自动调用单个参数的File构造方法,同时将filepath路径应用到File但构造参数 
  67.          * 如果dir为//,则此路径为本文件所在磁盘根目录 
  68.          */  
  69.         File f = new File(dir, filepath);  
  70.         if (f.exists()) {  
  71.         } else {  
  72.             f.mkdirs();  
  73.         }  
  74.   
  75.         String[] names = f.list(new FilenameFilter() { // 实现了FilenameFilter接口的匿名类,实现accept方法过滤文件   
  76.   
  77.                     @Override  
  78.                     public boolean accept(File dir, String name) {  
  79.                         System.out.println(name.indexOf(".java"));  
  80.                         return name.indexOf(".java") != -1;  
  81.                     }  
  82.                 });  
  83.   
  84.         for (int i = 0; i < names.length; i++) {  
  85.             System.out.println(names[i]);  
  86.         }  
  87.     }  
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数组通常扮演承接数据的中间角色。

Java代码   收藏代码
  1. public class FileStreamDemo {  
  2.       
  3.     public static void main(String[] args) {  
  4.           
  5.         try {  
  6.               
  7.             byte[] buffer = new byte[1024];  
  8.               
  9.             // 来源文件  
  10.             FileInputStream fileInputStream = new FileInputStream(new File(args[0]));  
  11.               
  12.             // 目的文件  
  13.             FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1]));  
  14.               
  15.             // available()可取得未读取的数据长度  
  16.             System.out.println("复制文件:" + fileInputStream.available() + "字节");  
  17.   
  18.             while (true) {  
  19.                 if (fileInputStream.available() < 1024) {  
  20.                     // 剩余的数据比1024字节少  
  21.                     // 一位一位读出再写入目的文件  
  22.                     int remain = -1;  
  23.                     while ((remain = fileInputStream.read()) != -1) {  
  24.                         fileOutputStream.write(remain);  
  25.                     }  
  26.                     break;  
  27.                 } else {  
  28.                     // 从来源文件读取数据至缓冲区  
  29.                     fileInputStream.read(buffer);  
  30.                     // 将数组数据写入目的文件  
  31.                     fileOutputStream.write(buffer);  
  32.                 }  
  33.             }  
  34.   
  35.             // 关闭流  
  36.             fileInputStream.close();  
  37.             fileOutputStream.close();  
  38.   
  39.             System.out.println("复制完成");  
  40.         } catch (ArrayIndexOutOfBoundsException e) {  
  41.             System.out.println("using: java FileStreamDemo src des");  
  42.             e.printStackTrace();  
  43.         } catch (IOException e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47. }  
  1. public class FileStreamDemo {  
  2.       
  3.     public static void main(String[] args) {  
  4.           
  5.         try {  
  6.               
  7.             byte[] buffer = new byte[1024];  
  8.               
  9.             // 来源文件   
  10.             FileInputStream fileInputStream = new FileInputStream(new File(args[0]));  
  11.               
  12.             // 目的文件   
  13.             FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1]));  
  14.               
  15.             // available()可取得未读取的数据长度   
  16.             System.out.println("复制文件:" + fileInputStream.available() + "字节");  
  17.   
  18.             while (true) {  
  19.                 if (fileInputStream.available() < 1024) {  
  20.                     // 剩余的数据比1024字节少   
  21.                     // 一位一位读出再写入目的文件   
  22.                     int remain = -1;  
  23.                     while ((remain = fileInputStream.read()) != -1) {  
  24.                         fileOutputStream.write(remain);  
  25.                     }  
  26.                     break;  
  27.                 } else {  
  28.                     // 从来源文件读取数据至缓冲区   
  29.                     fileInputStream.read(buffer);  
  30.                     // 将数组数据写入目的文件   
  31.                     fileOutputStream.write(buffer);  
  32.                 }  
  33.             }  
  34.   
  35.             // 关闭流   
  36.             fileInputStream.close();  
  37.             fileOutputStream.close();  
  38.   
  39.             System.out.println("复制完成");  
  40.         } catch (ArrayIndexOutOfBoundsException e) {  
  41.             System.out.println("using: java FileStreamDemo src des");  
  42.             e.printStackTrace();  
  43.         } catch (IOException e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47. }  
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

Java代码   收藏代码
  1. import java.io.PipedWriter;  
  2. import java.util.Random;  
  3.   
  4. class Sender extends Thread {  
  5.     private Random rand = new Random();  
  6.     private PipedWriter out = new PipedWriter();  
  7.   
  8.     public PipedWriter getPipedWriter() {  
  9.         return out;  
  10.     }  
  11.   
  12.     public void run() {  
  13.         while (true) {  
  14.             for (char c = 'A'; c <= 'z'; c++) {  
  15.                 try {  
  16.                     out.write(c);  
  17.                     sleep(rand.nextInt(500));  
  18.                 } catch (Exception e) {  
  19.                     throw new RuntimeException(e);  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  
  1. import java.io.PipedWriter;  
  2. import java.util.Random;  
  3.   
  4. class Sender extends Thread {  
  5.     private Random rand = new Random();  
  6.     private PipedWriter out = new PipedWriter();  
  7.   
  8.     public PipedWriter getPipedWriter() {  
  9.         return out;  
  10.     }  
  11.   
  12.     public void run() {  
  13.         while (true) {  
  14.             for (char c = 'A'; c <= 'z'; c++) {  
  15.                 try {  
  16.                     out.write(c);  
  17.                     sleep(rand.nextInt(500));  
  18.                 } catch (Exception e) {  
  19.                     throw new RuntimeException(e);  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  
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

Java代码   收藏代码
  1. import java.io.IOException;  
  2. import java.io.PipedReader;  
  3.   
  4. class Receiver extends Thread {  
  5.     private PipedReader in;  
  6.   
  7.     public Receiver(Sender sender) throws IOException {  
  8.         in = new PipedReader(sender.getPipedWriter());  
  9.     }  
  10.   
  11.     public void run() {  
  12.         try {  
  13.             while (true) {  
  14.                 // Blocks until characters are there:  
  15.                 System.out.println("Read: " + (char) in.read());  
  16.             }  
  17.         } catch (IOException e) {  
  18.             throw new RuntimeException(e);  
  19.         }  
  20.     }  
  21. }  
  1. import java.io.IOException;  
  2. import java.io.PipedReader;  
  3.   
  4. class Receiver extends Thread {  
  5.     private PipedReader in;  
  6.   
  7.     public Receiver(Sender sender) throws IOException {  
  8.         in = new PipedReader(sender.getPipedWriter());  
  9.     }  
  10.   
  11.     public void run() {  
  12.         try {  
  13.             while (true) {  
  14.                 // Blocks until characters are there:   
  15.                 System.out.println("Read: " + (char) in.read());  
  16.             }  
  17.         } catch (IOException e) {  
  18.             throw new RuntimeException(e);  
  19.         }  
  20.     }  
  21. }  
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

Java代码   收藏代码
  1. public class PipedIO {  
  2.       
  3.     public static void main(String[] args) throws Exception {  
  4.         Sender sender = new Sender();  
  5.         Receiver receiver = new Receiver(sender);  
  6.         sender.start();  
  7.         receiver.start();  
  8.     }  
  9. }  
  1. public class PipedIO {  
  2.       
  3.     public static void main(String[] args) throws Exception {  
  4.         Sender sender = new Sender();  
  5.         Receiver receiver = new Receiver(sender);  
  6.         sender.start();  
  7.         receiver.start();  
  8.     }  
  9. }  
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

Java代码   收藏代码
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedOutputStream;  
  5.   
  6. public class Sender1 extends Thread {  
  7.   
  8.     private PipedOutputStream pos;  
  9.       
  10.     private File file;  
  11.   
  12.     // 构造方法  
  13.     Sender1(PipedOutputStream pos, String fileName) {  
  14.         this.pos = pos;  
  15.         file = new File(fileName);  
  16.     }  
  17.   
  18.     // 线程运行方法  
  19.     public void run() {  
  20.         try {  
  21.             // 读文件内容  
  22.             FileInputStream fs = new FileInputStream(file);  
  23.             int data;  
  24.             while ((data = fs.read()) != -1) {  
  25.                 // 写入管道始端  
  26.                 pos.write(data);  
  27.             }  
  28.             pos.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Sender Error" + e);  
  31.         }  
  32.     }  
  33. }  
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedOutputStream;  
  5.   
  6. public class Sender1 extends Thread {  
  7.   
  8.     private PipedOutputStream pos;  
  9.       
  10.     private File file;  
  11.   
  12.     // 构造方法   
  13.     Sender1(PipedOutputStream pos, String fileName) {  
  14.         this.pos = pos;  
  15.         file = new File(fileName);  
  16.     }  
  17.   
  18.     // 线程运行方法   
  19.     public void run() {  
  20.         try {  
  21.             // 读文件内容   
  22.             FileInputStream fs = new FileInputStream(file);  
  23.             int data;  
  24.             while ((data = fs.read()) != -1) {  
  25.                 // 写入管道始端   
  26.                 pos.write(data);  
  27.             }  
  28.             pos.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Sender Error" + e);  
  31.         }  
  32.     }  
  33. }  
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

Java代码   收藏代码
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedInputStream;  
  5.   
  6. public class Receiver1 extends Thread {  
  7.   
  8.     private PipedInputStream pis;  
  9.     private File file;  
  10.   
  11.     // 构造方法  
  12.     Receiver1(PipedInputStream pis, String fileName) {  
  13.         this.pis = pis;  
  14.         file = new File(fileName);  
  15.     }  
  16.   
  17.     // 线程运行  
  18.     public void run() {  
  19.         try {  
  20.             // 写文件流对象  
  21.             FileOutputStream fs = new FileOutputStream(file);  
  22.             int data;  
  23.             // 从管道末端读  
  24.             while ((data = pis.read()) != -1) {  
  25.                 // 写入本地文件  
  26.                 fs.write(data);  
  27.             }  
  28.             pis.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Receiver Error" + e);  
  31.         }  
  32.     }  
  33. }  
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedInputStream;  
  5.   
  6. public class Receiver1 extends Thread {  
  7.   
  8.     private PipedInputStream pis;  
  9.     private File file;  
  10.   
  11.     // 构造方法   
  12.     Receiver1(PipedInputStream pis, String fileName) {  
  13.         this.pis = pis;  
  14.         file = new File(fileName);  
  15.     }  
  16.   
  17.     // 线程运行   
  18.     public void run() {  
  19.         try {  
  20.             // 写文件流对象   
  21.             FileOutputStream fs = new FileOutputStream(file);  
  22.             int data;  
  23.             // 从管道末端读   
  24.             while ((data = pis.read()) != -1) {  
  25.                 // 写入本地文件   
  26.                 fs.write(data);  
  27.             }  
  28.             pis.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Receiver Error" + e);  
  31.         }  
  32.     }  
  33. }  
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

Java代码   收藏代码
  1. import java.io.IOException;  
  2. import java.io.PipedInputStream;  
  3. import java.io.PipedOutputStream;  
  4.   
  5. public class PipedIO1 {  
  6.   
  7.     public static void main(String[] args) {  
  8.         try {  
  9.             // 构造读写的管道流对象  
  10.             PipedInputStream pis = new PipedInputStream();  
  11.             PipedOutputStream pos = new PipedOutputStream();  
  12.               
  13.             // 实现关联  
  14.             pos.connect(pis);  
  15.               
  16.             // 构造两个线程,并且启动。  
  17.             new Sender1(pos, "c:\\a1.txt").start();  
  18.             new Receiver1(pis, "c:\\a2.txt").start();  
  19.         } catch (IOException e) {  
  20.             System.out.println("Pipe Error" + e);  
  21.         }  
  22.     }  
  23. }  
  1. import java.io.IOException;  
  2. import java.io.PipedInputStream;  
  3. import java.io.PipedOutputStream;  
  4.   
  5. public class PipedIO1 {  
  6.   
  7.     public static void main(String[] args) {  
  8.         try {  
  9.             // 构造读写的管道流对象   
  10.             PipedInputStream pis = new PipedInputStream();  
  11.             PipedOutputStream pos = new PipedOutputStream();  
  12.               
  13.             // 实现关联   
  14.             pos.connect(pis);  
  15.               
  16.             // 构造两个线程,并且启动。   
  17.             new Sender1(pos, "c:\\a1.txt").start();  
  18.             new Receiver1(pis, "c:\\a2.txt").start();  
  19.         } catch (IOException e) {  
  20.             System.out.println("Pipe Error" + e);  
  21.         }  
  22.     }  
  23. }  
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

Java代码   收藏代码
  1. import java.io.IOException;  
  2. import java.io.RandomAccessFile;  
  3.   
  4. public class RandomFileRW {  
  5.   
  6.     public static void main(String args[]) {  
  7.         StringBuffer buf = new StringBuffer();  
  8.         char ch;  
  9.           
  10.         try {  
  11.             while ((ch = (char) System.in.read()) != '\n') {  
  12.                 buf.append(ch);  
  13.             }  
  14.               
  15.             // 读写方式可以为"r" or "rw"  
  16.               
  17.             /** 
  18.              * @param mode 1. r 2. rw 3. rws 4. rwd 
  19.              * "r" Open for reading only. Invoking any of the write methods of the resulting object will 
  20.              *      cause an IOException to be thrown.   
  21.              * "rw" Open for reading and writing. If the file does not already exist then an attempt will 
  22.              *      be made to create it.   
  23.              * "rws" Open for reading and writing, as with "rw", and also require that every update to the 
  24.              *      file's content or metadata be written synchronously to the underlying storage device.   
  25.              * "rwd"   Open for reading and writing, as with "rw", and also require that every update to the 
  26.              *      file's content be written synchronously to the underlying storage device.  
  27.              */  
  28.             RandomAccessFile myFileStream = new RandomAccessFile("c:\\UserInput.txt""rw");  
  29.             myFileStream.seek(myFileStream.length());  
  30.             myFileStream.writeBytes(buf.toString());  
  31.               
  32.             // 将用户从键盘输入的内容添加到文件的尾部  
  33.             myFileStream.close();  
  34.         } catch (IOException e) {  
  35.         }  
  36.     }  
  37. }  
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号