Java入门系列-22-IO流

File类的使用

Java程序如何访问文件?通过 java.io.File 类

使用File类需要先创建文件对象 File file=new File(String pathname);,创建时在构造函数中指定物理文件或目录,然后通过文件对象的方法操作文件或目录的属性。

\ 是特殊字符,要使用需要转义 \\

File 类常用方法

方法名称说明
boolean exists()判断文件或目录是否存在
boolean isFile()判断是否是文件
boolean isDirectory()判断是否是目录
String getPath()返回此对象表示的文件的相对路径名
String getAbsolutePath()返回此对象表示的文件的绝对路径
String getName()返回此对象指定的文件或目录
boolean createNewFile()创建名称的空文件,不创建文件夹
long length()返回文件的长度,单位为字节,文件不存在则返回0L
File[] listFiles()返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。
static File[] listRoots()列出可用文件系统根
boolean mkdirs()创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。

使用示例:

import java.io.File;
import java.io.IOException;

public class TestFile {

	public static void main(String[] args) {
		//创建File对象 传入文件的路径
		File file=new File("D:\\a.txt");
		//创建File对象 传入文件夹的路径
		File dir=new File("D:/word");
		//判断是否存在
		if(file.exists()) {
			if(file.isFile()) {
				//getName()获取名字
				System.out.println(file.getName()+" 是文件");
			}else if(file.isDirectory()){
				System.out.println(file.getName()+" 是目录");
			}			
		}else {
			System.out.println(file.getName()+" 不存在!");
			try {
				//创建文件
				file.createNewFile();
				System.out.println("文件大小:"+file.length()+" 字节");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(dir.exists()) {
			if(dir.isFile()) {
				System.out.println(dir.getName()+" 是文件");
			}else if(dir.isDirectory()) {
				System.out.println(dir.getName()+" 是文件夹");
				//绝对路径
				System.out.println(dir.getAbsolutePath());
			}			
		}else {
			System.out.println(dir.getName()+" 不存在!");
			//创建目录
			dir.mkdirs();
		}
		
	}
}

:指一连串流动的字符,是以先进先出方式发送信息的通道

输入流:源数据流向程序(读)

输入流:程序中的数据流向目标数据源(写)

Java流的分类

按流向

  • 输出流(OutputStream和Writer作为基类)
  • 输入流(InputStream和Reader作为基类)

输入输出流是相对于计算机内存来说的

按照处理数据单元划分

  • 字节流
    • 字节输入流(InputStream基类)
    • 字节输出流(OutputStream基类)
  • 字符流
    • 字符输入流(Reader基类)
    • 字符输出流(Writer基类)

字节流是8位(1B)通用字节流,字符流是16位(2B)Unicode字符流

字节流

FileInputStream 是 InputStream 的子类

InputStream 类常用方法

方法名称说明
int read()从输入流中读取数据的下一个字节。返回0到255的int值,如果到达流的末尾,则返回-1
int read(byte[] b)从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。返回读入缓冲区的总字节数,如果达到末尾则返回-1
int read(byte[] b,int off,int len)将输入流中最多 len 个数据字节读入 byte数组
void close()关闭此输入流并释放与该流关联的所有系统资源
int available()返回此输入流下一个方法调用可以不受阻塞地从此输入流读取的估计字节数

FileInputStream 类常用构造方法

名称说明
FileInputStream(File file)通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。
FileInputStream(String name)通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。

使用 FileInputStream 读取文件

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TestFileInputStream {

	public static void main(String[] args) {
		FileInputStream fis=null;
		try {
			fis=new FileInputStream("D:\\a.txt");
			//读取结果存入StringBuffer
			StringBuffer sb=new StringBuffer();
			System.out.println("预计读取:"+fis.available()+"字节");
			//记录每次读取的长度
			int len=0;
			//缓冲区字节数组
			byte[] buff=new byte[1024];
			while((len=fis.read(buff))!=-1) {
				System.out.println("还剩余:"+fis.available()+"字节");
				sb.append(new String(buff,0,len));
			}
			System.out.println("结果:");
			System.out.println(sb);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (fis!=null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

FileOutputStream 是 OutputStream 的子类

OutputStream 类常用方法

方法名称说明
void write(int c)将制定的字节写入此输出流
void write(byte[] buf)将 b.length 个字节从指定的 byte 数组写入此输入流
void write(byte[] b,int off,int len)将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流
void close()关闭此输出流并释放与此流有关的所有系统资源

FileOutputStream的构造方法

名称说明
FileOutputStream(File file)创建一个向指定 File 对象表示的文件中写入数据的文件输出流
FileOutputStream(String name)创建一个向具有指定名称的文件中写入数据的输出文件流
FileOutputStream(String name,boolean append)第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处

使用 FileOutputStream 写文件

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestFileOutputStream {

	public static void main(String[] args) {
		FileOutputStream fos=null;
		try {
			//创建输出流对象
			fos=new FileOutputStream("D:\\c.txt");
			//要输出的字符
			String str="hello world 你好";
			//将字符串转成字节数组并写入到流中
			fos.write(str.getBytes());
			//刷新流
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (fos!=null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

字符流

上面的内容我们看到,字节流不能直接操作字符,所以操作字符用字符流。

FileReader 是 Reader 的子类

Reader 类常用方法

方法名称说明
int read()读取单个字符
int read(char[] c)将字符读入数组
read(char[] c,int off,int len)将字符读入数组的某一部分
void close()关闭该流并释放与之关联的所有资源

使用 FileReader 读取文本文件

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class TestReader {

	public static void main(String[] args) {
		Reader r=null;
		try {
			//创建FileReader对象
			r=new FileReader("D:\\a.txt");
			//字符缓冲数组
			char[] chrs=new char[512];
			//记录每次读取的个数
			int len=0;
			//循环读取
			while((len=r.read(chrs))!=-1) {
				String str=new String(chrs, 0, len);
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (r!=null) {
				try {
					r.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

FileWriter 是 Writer 的子类

Writer 类常用方法

方法名称说明
write(String str)写入字符串
write(String str,int off,int len)写入字符串的某一部分
void close()关闭此流,但要先刷新它
void flush刷新该流的缓冲

使用 FileWriter 写入文本文件

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class TestWriter {

	public static void main(String[] args) {
		Writer w=null;
		try {
			//创建字符输出流
			w=new FileWriter("D:\\msg.txt");
			String msg="hello every bady 兄嘚";
			//将字符串写入到流中
			w.write(msg);
			w.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (w!=null) {
				try {
					w.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

缓冲字符流

如果频繁的对字符进行读写操作,墙裂建议使用缓冲!

BufferedReader 类带有缓冲区,可以先把一批数据读到缓冲区,接下来的读操作都是从缓冲区内获取数据,避免每次都从数据源读取数据进行字符编码转换,从而提高读取操作的效率。

使用BufferedReader读取文本文件

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestBufferedReader {

	public static void main(String[] args) {
		FileReader reader=null;
		BufferedReader br=null;
		try {
			//创建字符读入流
			reader=new FileReader("D:\\a.txt");
			//将字符读入流包装成字符缓冲流
			br=new BufferedReader(reader);
			//记录每行读入的内容
			String line=null;
			//用于拼接保存每行读入的内容
			StringBuffer content=new StringBuffer();
			while ((line=br.readLine())!=null) {
				content.append(line+"\n");
			}
			System.out.println("所有内容:");
			System.out.println(content);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (reader!=null) {
					reader.close();
				}
				if (br!=null) {
					br.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

BufferedReader 是 Reader 的子类,带有缓冲区,特有方法 readLine() 按行读取内容

BufferedWriter 类带有缓冲区,与BufferedReader的方向正好相反,BufferedWriter 是把一批数据写到缓冲区,当缓冲区满的时候,再把缓冲区的数据写到字符输出流中。避免每次都执行物理写操作,提高写操作的效率。

使用 BufferedWriter 写文件

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class TestBufferedWriter {

	public static void main(String[] args) {
		FileWriter writer=null;
		BufferedWriter bw=null;
		try {
			writer=new FileWriter("D:\\out.txt");
			bw=new BufferedWriter(writer);
			bw.write("hello");
			//内容换行
			bw.newLine();
			bw.write("world");
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (bw!=null) {
					bw.close();
				}
				if (writer!=null) {
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

关闭流的顺序与创建流的顺序相反

数据流

DataInputStream 类

  • FileInputStream 的子类
  • 与 FileInputStream 类结合使用读取二进制文件

DataOutputStream 类

  • FileOutputStream 的子类
  • 与 FileOutputStream 类结合使用写二进制文件

使用数据流复制图片

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestCopy {

	public static void main(String[] args) {
		//文件输入流
		FileInputStream fis=null;
		//数据输入流(包装fis得到)
		DataInputStream dis=null;
		//文件输出流
		FileOutputStream fos=null;
		//数据输出流(包装fos得到)
		DataOutputStream dos=null;
		
		try {
			fis=new FileInputStream("D:\\a.jpg");
			dis=new DataInputStream(fis);
			fos=new FileOutputStream("F:\\b.jpg");
			dos=new DataOutputStream(fos);
			//缓冲数组
			byte[] buff=new byte[1024];
			//记录每次读取的字节个数
			int len=0;
			//循环读入
			while((len=dis.read(buff))!=-1) {
				//循环写入len个字节
				dos.write(buff,0,len);
			}
			System.out.println("完成");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (dis!=null) {
					dis.close();
				}
				if (dos!=null) {
					dos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值