IO总结


Java IO 总结

第一部分

                  File ——操作文件的类

    位于java.io包下的File类,可以通过创建File类对象的方法创建文件对象,删除文件,列表目录下的文件,但是,通过此类修改文件内容或者文件名还做不到。

一.创建File对象——构造方法

   File有如下构造器:

   File(File parent,String child) 在一个目录下创建一个名为chile的文件

   File(String pathname)  创建一个指向pathname名字的对象——————————(常用)

   File(String parent,String pathname)以一个名为parent的目录下创建一个指向pathname的文件

二.调用方法——File类的重要方法

   boolean exists() 判断文件是否存在

   String getName()

   boolean  isDirectory()是否为目录

   boolean isFile()判断是否是真实文件

   File[] listFiles()     返回File对象指向的文件的下一级的所有目录和文件

   static File[] listRoots()     返回机器上所有根目录

三.示例——递归算法查找文件

public int findDir(String pathname) {
		// 用来记录文件的个数
		int fileCount = 0;
               //创建文件类对象
                File dirFile=new  File(pathname);
       
		File[] subFile = dirFile.listFiles();// 列表目录,返回此文件下一级所有目录和文件
		if (subFile == null || subFile.length == 0) {
			return 0;
		}

		// 遍历一级子目录
		for (int i = 0; i < subFile.length; i++) {
			if (subFile[i].isDirectory()) {//如果是目录
                               //得到此目录的绝对路径
				String subDir = subFile[i].getAbsolutePath();
				// 如果还是目录,则递归调用进行计算,参数为文件类型
				fileCount += findDir(subDir);
			} else if (subFile[i].isFile()) {
				fileCount++;
				String fileName = subFile[i].getAbsolutePath();// 得到绝对路径

				
			}
		}
		
		return fileCount;

		
 

第二部分

          流的概念与应用

  将Java中输入输出抽象为流的概念,输入流是我们从某个地方读取数据,输出流式将数据发送到某个地方,即写入。

流的分类

 最基本,按方向分为输入流(InputStream)和输出流(OutputStream),它们是抽象类,有多种适用与不同用途的具体实现类。现以其中的三个子类:FileInputStream,BufferedInputStream和DataInputStream和对于的FileOutputStream,BufferedOutputStream和DataOutputStream讲解示范流的基础应用。

1)

A    FileInputStream读取数据

public String readFile(String filename)throws IO exception {
        
          // 通过文件对象创建输入流
          File srcFile=new File(filename);
         //创建一个输入流对象
           InputStream ins=new FileInputStream(filename);
        //根据流中的字节长度,创建byte数组保存读到的数据
          byte[] conetentByte=new byte[ins.available()];
       //将流中的数据读到数组中
        ins.read(conetentByte);
         //将byte数组转换为字符串
          String s=new  String(conetentByte);
         return s;
}
 

InputStream中还定义一个read()方法,每次调用读取一个字节,与上区别在于:定义byte数组后,

         int count=0;//表示读取到第几个字节

             //java中定义-1表示读完了

        while((i=ins.read())!=-1){

               /将读到的byte数字读入到数组中

                 contentByte[count]=(byte)i;

                 count++;

              }

B  FileOutputStream写入数据

public boolean copyFile(File srcname,File  destFile)throws IOException{
               InputStream ins=new FileInputStream(srcname);
               OutputStream out=new FileOutputStream(destFile);
               int i=0;
               //从输入流中读取一个字节
                while((i=ins.read())!=-1){
                        //写到输出流
                        out.write(i);
                     }
               ins.close();
               out.flush();
               out.close();
                 //记住,此处必须及时关闭各种流
             return true;
}
        
 

2)Buffered流,也叫缓冲流。在上面一般流的基础上增加了一个缓冲输入输出流,简单的理解,文件输入流将字节一个一个的传入缓冲流,一起读取并写到缓冲输出流,较普通流一个字节一个字节的传送,效率明显的提高。读者可以自己写一个小的测试程序,会发现效率还是挺大的。此外,这就要求Biffered流完成写入后,必须及时关闭流,不然,会一直读取,甚至覆盖缓冲流之前的数据。而一般流则无需注意这些。

C.Data流——用来读写指定的数据类型,可以很容易的实现将数据保存到文件中和从文件中读取出来,具体应用看下面文件保存的代码中。

第三部分

          文件保存

 根据文件格式实现文件保存和读取,不同的文件格式就是将文件的信息用不同的顺序和表达写到存储器中,计算机有自带的文件格式,我们也可以定义属于自己的格式,先以画图板文件保存为例讲解:

首先,要知道,文件一般有两个部分组成,一是文件头信息,如画图板中每一张图的格式,宽,高等,另一部分是文件的数据信息,如图中每个像素点的坐标,颜色等。

其次,实现画板保存,首先要得到屏幕上的画图,即截屏。

public class ScreenCapture {
	
	public int[][] createCapture(JPanel panel) throws AWTException{
		//获取到画图面板的宽和高
		int width =panel.getWidth();
		int height=panel.getHeight();
		
		//获取画板相对屏幕的坐标
		Point point=panel.getLocationOnScreen();
		//实例化一个矩形形象
		Rectangle rect=new Rectangle((int)point.getX(),(int)point.getY(),width,height);

		//实例化一个robot对象
		Robot robot=new Robot();
		//截屏
		BufferedImage image=robot.createScreenCapture(rect);

		//实例化一个二维数组,存储每个像素的值
		int[][] array=new  int[width][height];

		//遍历图片,取出输出到数组中
		for(int i=0;i<array.length ;i++){
			 for(int j=0;j<array[i].length ;j++){
				 array[i][j]=image.getRGB(i, j);
			 }
		}
		return array;
		
		
	}
	

}

再者,就是根据截屏图片编写文件保存和读取的方法

 public class FileTest {

	/**
	 * 保存画板数据成文件
	 * 
	 * @param 需要参数,保存文件的路径名,保存像素点的数组
	 */
	public boolean saveFile(String path, int[][] array) {
		boolean result = false;
		try {
			// 文件输出流
			OutputStream fos = new FileOutputStream(path);
			BufferedOutputStream bos=new BufferedOutputStream(fos);
			// 将文件输出流包装成可写基本类型的流
			DataOutputStream dos = new DataOutputStream(bos);
		
			// 写文件头
			dos.writeInt(array.length);// 宽度,列
			dos.writeInt(array[0].length);// 高度,行
			// 文件内容
			for (int i = 0; i < array.length; i++) {
				for (int j = 0; j < array[i].length; j++) {
                                        //将每个点的信息写入流中
					dos.writeInt(array[i][j]);
				}
			}
			// 文件保存成功
			result = true;  
			
			dos.close();
			bos.close();
			fos.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result;

	}
 
/**
	 * 打开文件的方法
	 * 
	 * @param path
	 * @return
	 */
	public int[][] readFile(String path) {
		// 创建一个数组存储读取的内容
		int array[][] = null;
		try {
			// 创建文件对象的输入流
			InputStream fis = new FileInputStream(path);
			BufferedInputStream bis=new BufferedInputStream(fis);
			// 将文件输入流包装成可读基本类型的流
			DataInputStream dis = new DataInputStream(bis);
			// 读取文件头
			int width = dis.readInt();// 宽度,列
			int height = dis.readInt();// 高度,行
			// 实例化数组
			array = new int[width][height];
			// 写文件内容
			for (int i = 0; i < array.length; i++) {
				for (int j = 0; j < array[i].length; j++) {
					array[i][j] = dis.readInt();
				}
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return array;

	}
 

最后,在菜单栏中点击Save或Open时调用相应方法即可。当然,还有更为重要的是,画板重绘。打开文件的时候我们只是读取到这些信息,并没有显示在屏幕上。只能在画板重绘重写paint()方法中,得到改像素数组,遍历画出即可。具体实现代码读者可以自行尝试。

第四部分

             结束语

IO操作主要指的是使用Java进行输入,输出操作,java中的所有操作类都在此包中,此包中最重要的就是5个类和一个接口,即File,OutputStream,InputStream,Writer,Reader和Serializable接口,掌握这些就是掌握IO的核心,这里没有详细介绍的其余部分,读者若感兴趣可以翻阅书籍进行查阅与学习。

猜你喜欢

转载自csu-ningman.iteye.com/blog/1595400