Java基础——IO流

IO流
1.java.io.File
  1.凡是与输入输出相关的类、接口都定义在java.io下
  2.File是一个类,可以由构造器创建其对象。此对象对应着一个文件(.txt .avi .ppt .doc .mp3 .jpg)或文件目录
  3.File类对象是与平台无关的(Java的跨平台特性)
  4.File中的方法,仅涉及到如何创建,删除,重命名等(表面功夫),只要涉及到文件内容的,File是无能为力的,必须由io流来完成
  5.File类的对象常常作为io流的具体类的构造器的形参

  访问文件名:
    getName()
    getPath()
    getAbsoluteFile()
    getAbsolutePath()
    getParent()
    renameTo(File newName)//重命名
      boolean b = file1.renameTo(file2);//要求1.file1文件存在,file2文件不存在。2.file1 file2 类型相同(文件或文件目录)

  文件检测
    exists()
    canWrite()
    canRead()
    isFile()
    isDirectory()

  获取常规文件信息
    lastModified()
    length()

  文件操作相关
    createNewFile()
    delete()

  目录操作相关
    mkDir() //创建一个文件目录,只有在上层文件目录存在的情况下,才返回true
    mkDirs()//创建一个文件目录,若上层文件目录不存在,一并创建
    list() //返回当前文件夹下的内容,是String[]形式的 String[] str = file1.list();
    listFiles()//返回当前文件夹下的内容,是File[]形式的,可以继续后面对文件的操作 File[] files = file1.listFiles();

IO流
  1.流的分类
    按操作数据单位不同分为:字节流(8 bit),字符流(16 bit)(处理的文本文件)
    按数据流的流向不同分为:输入流,输出流
    按流的角色的不同分为:节点流(直接作用于文件的),处理流

  2.IO的体系:
    抽象基类     结点流(文件流)     缓冲流(处理流的一种,可以提升文件操作的效率
    InputStream   FileInputStream       BufferedInputStream
    OutputStream   FileOutputStream       BufferedOutputStream (flush())
    Reader     FileReader          BufferedReader(String readLine(file);)//还可以一行一行的读取
    Writer       FileWriter             BufferedWriter (flush()) 
   

  doc文件要复制要用字节流,不能用字符流

注:String readLine(file); 中是读不到换行的,若想写的话,要自己加bw.write(str + " ") ;或者 bw.newLine();
  对于非文本文件(视频,图片,音频),只能使用字节流实现文件的复制FileInputStream、FileOutputStream
  对于文本文件,还可以只用字符流FileReader、FileWriter

FileReader、FileWriter
在使用时,只是在读取那里char[] c = new char[20];其他地方与 FileInputStream、 FileOutputStream差不多

字节流的文件读取操作

@Test
	public void testInputFileStream1() {
		//2.创建一个FileInputStream类的对象
		FileInputStream fis = null;
		try {
			//1.创建一个File类的对象
			File file = new File("tests.txt");
			fis = new FileInputStream(file);
			//3.调用FileInputStream的方法,实现file文件的读取
			/*public int read(byte[] b)
			 *读取文件的一个字节,当执行到文件结尾时,返回-1 
			 */
			byte[] b = new byte[5];
			int len;
			while((len = fis.read(b)) != -1) {
				String str = new String(b, 0, len);//注意不是b.length,否则最后一步没有覆盖完的字符也会输出出来
				System.out.print(str);
			}
		}  catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				//4.关闭相应的流
				fis.close(); 
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
	
	//使用try-catch方式处理异常更合理:保证流关闭操作一定可以执行
	@Test
	public void testInputFileStream() {
		//2.创建一个FileInputStream类的对象
		FileInputStream fis = null;
		try {
			//1.创建一个File类的对象
			File file = new File("tests.txt");
			fis = new FileInputStream(file);
			//3.调用FileInputStream的方法,实现file文件的读取
			/*
			 *read():读取文件的一个字节,当执行到文件结尾时,返回-1 
			 */
			int b;
			while((b = fis.read()) != -1) {
				System.out.print((char)b);
			}
		}  catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				//4.关闭相应的流
				fis.close(); 
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

  

@Test
	public void testFileOutputStream() {
		//1.创建一个File对象,指明要写入的文件位置
		//输出的物理文件可以不存在,当执行过程中,若不存在,会自动创建。若存在,会将原有的文件覆盖
		File file = new File("Love.txt");
		//2.创建一个FileOutputStream类的对象,将file的对象作为形参传递给FileOutputStream	的构造器中
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			//3.调用FileOutputStream的方法,进行写入操作
			//fos.write("I love China!");
			fos.write(new String("I love you! I love China").getBytes());
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(fos != null) {
				try {
					//4.关闭对应的文件
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}

	}

  字符流的文件读取操作

//从硬盘读取一个文件,并写入到另一个位置(相当于复制)
	@Test
	public void testCopyFile() {
		
		long start = System.currentTimeMillis();
		String src = new String("C:\Users\hasee\Desktop\QQ截图20171106155140.png");
		String dest = new String("C:\Users\hasee\Desktop\4.jpg");
		copyFile(src, dest);
		long end = System.currentTimeMillis();
		System.out.println("花费的时间为: " + (end - start));
	}
	
	public void copyFile(String src, String dest){
//		File file1 = new File("Love");//注意后缀,有和没有是不同的
//		File file2 = new File("Love2.txt");
		//File file1 = new File("C:\Users\hasee\Desktop\QQ截图20171107180120.png");//注意后缀,有和没有是不同的
		File file1 = new File(src);
		File file2 = new File(dest);//两种格式都可以复制过来
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(file1);
			fos = new FileOutputStream(file2);
			
			byte[] b = new byte[5];
			int len;
			while((len = fis.read(b)) != -1) {
				//fos.write(b);错误的写法两种:fos.write(b, 0, b.length);
				fos.write(b, 0, len);
			}
		}catch(Exception e){
			e.printStackTrace();
		} finally {
			if(fos != null) {
				try {
					fos.close();
				}catch(IOException e) {
					e.printStackTrace();
				}finally {
					if(fis != null) {
						try {
							fis.close();
						}catch(IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

  缓冲流的文件读取操作(一般推荐使用缓冲流直接操作文件,效率更快)

package test;
import java.io.*;
import org.junit.Test;

public class TestBuffered {
	@Test
	public void TestCopyFile() {
		
		long start = System.currentTimeMillis();
		String src = new String("Love.txt");
		String dest = new String("hello2.txt");
		copyFile(src, dest);
		long end = System.currentTimeMillis();
		System.out.println("总的输出时间为:" + (end - start));
	}
	public void copyFile(String src, String dest) {
		//1.提供读入、写出文件
		File file1 = new File(src);
		File file2 = new File(dest);
		
		//2.创建相应的节点流,FileInputStream、FileOutputStream
		//3.将创建的节点流的对象作为参数传递给缓冲器的构造器
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			FileInputStream fis = new FileInputStream(file1);
			FileOutputStream fos = new FileOutputStream(file2);
			
			bis = new BufferedInputStream(fis);
			bos = new BufferedOutputStream(fos);
			//4.具体的文件复制操作
			byte[] b = new byte[5];
			int len;
			while((len = bis.read(b)) != -1) {
				bos.write(b, 0, len);
				bos.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//5.关闭相应的流
			if(bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					if(bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
	
}

  


原文地址:https://www.cnblogs.com/SkyeAngel/p/7808784.html