IO
- 应用程序需要和外部设备进行数据交互,最常见的外部设备包含磁盘和网络
- IO就是指应用程序对这些设备的数据输入输出
- IO分为两大块
- File类,处理文件本身
- 流类,对文件内容进行读写操作
- File
- 一个File类的对象,表示了磁盘上的文件或者目录
- File类提供了一些与平台无关的方法来操纵文件
- File类提供了各种方法
- 创建删除重命名文件
- 判断文件是否存在和读写权限
- 设置和查询文件最近修改时间等操作
- 不能够编辑文件
创建File对象的几种方法
- package com.itlwc;
- import java.io.File;
- import java.io.IOException;
- public class IO {
- public static void main(String[] args) {
- File file = new File("d:\\文件夹");
- //创建目录(必须的)
- file.mkdir();
- // 第一种方法
- File file1 = new File("d:\\文件夹\\a.txt");
- // 第二种方法
- File file2 = new File("d:" + File.separatorChar + "文件夹"
- + File.separatorChar + "b.txt");
- // 第三种方法
- File file3 = new File("d:", "文件夹\\c.txt");
- // 第四种方法
- File file4 = new File("d:\\文件夹", "d.txt");
- // 第五种方法
- File file5 = new File(new File("d:\\文件夹"), "e.txt");
- try {
- file1.createNewFile();
- file2.createNewFile();
- file3.createNewFile();
- file4.createNewFile();
- file5.createNewFile();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
File的常用方法
- package com.itlwc;
- import java.io.File;
- import java.io.IOException;
- public class IO {
- public static void main(String[] args) {
- // 创建目录
- createDir("d:\\文件夹");
- // 创建文件
- createFile("d:\\文件夹\\t.txt");
- // 删除文件
- deleteFile("d:\\文件夹\\t.txt");
- // 删除目录
- delDirectory(new File("d:\\文件夹"));
- }
- public static void createDir(String pathName) {
- File f = new File(pathName);
- f.mkdirs();
- // 文件或目录是否存在
- if (f.exists()) {
- System.out.println("目录创建成功");
- }
- }
- public static void createFile(String pathName) {
- File f = new File(pathName);
- try {
- if (f.exists()) {
- System.out.println("文件已经存在");
- } else {
- f.createNewFile();
- System.out.println("创建成功");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public static void deleteFile(String pathName) {
- File f = new File(pathName);
- if (f.exists()) {
- // 删除此抽象路径名表示的文件或目录
- f.delete();
- if (f.exists()) {
- System.out.println("删除失败");
- } else {
- System.out.println("删除成功");
- }
- } else {
- System.out.println("文件已经不存在");
- }
- }
- public static void delDirectory(File fileList) {
- File[] files = fileList.listFiles();
- for (int i = 0; i < files.length; i++) {
- if (files[i].isFile()) {
- files[i].delete();
- } else {
- delDirectory(files[i]);
- }
- }
- fileList.delete();
- }
- }
File类查找文件的几种方法
- package com.itlwc;
- import java.io.File;
- public class IO {
- public static void main(String[] args) {
- File file = new File("d:\\文件夹");
- // 返回String类型(不返回子文件)
- String[] str = file.list();
- for (String s : str) {
- System.out.println(s);
- }
- System.out.println("---------------");
- // 返回File类型(不返回子文件)
- File[] f = file.listFiles();
- for (File fi : f) {
- System.out.println(fi.getName());
- }
- System.out.println("---------------");
- // 递归返回所有文件包括子文件
- findFile(file);
- }
- public static void findFile(File fileList) {
- File[] files = fileList.listFiles();
- for (int i = 0; i < files.length; i++) {
- if (files[i].isFile()) {
- System.out.println(files[i].getName());
- } else {
- if (files[i].listFiles().length > 0) {
- System.out.println(files[i].getName());
- findFile(files[i]);
- } else {
- System.out.println(files[i].getName());
- }
- }
- }
- }
- }
- /*
- 打印结果:
- a.txt
- 新建文件夹
- ---------------
- a.txt
- 新建文件夹
- ---------------
- a.txt
- 新建文件夹
- b.txt
- */
递归查看文件夹结构图
- package com.itlwc;
- import java.io.File;
- public class Test {
- public static void main(String[] args) {
- File file = new File("d:\\KwDownload");
- listChids(file, 0);
- }
- public static void listChids(File f, int level) {
- String preSrt = "";
- for (int i = 0; i < level; i++) {
- preSrt += "----";
- }
- System.out.println(preSrt + f.getName());
- if (!f.isDirectory()) {
- return;
- } else {
- File[] fs = f.listFiles();
- for (int i = 0; i < fs.length; i++) {
- listChids(fs[i], level + 1);
- }
- }
- }
- }
- /*
- KwDownload
- ----abc.jnt
- ----Lyric
- --------Lenka-Trouble Is A Friend (麻烦是个朋友).lrc
- --------S.H.E-安全感.lrc
- --------大庆小芳-败家娘们儿.lrc
- ----song
- --------zjd
- ------------大庆小芳-败家娘们儿.mp3
- --------大庆小芳-败家娘们儿.mp3
- ----Temp
- --------175B801812D20FF0.aac
- --------2A94710E1FB7FC13.wma
- --------475724778F0B2848.wma
- --------544A55A6B2DA2305.exe
- --------6F7B9764DF582BF1.wma
- --------C64DFA53A508C6BE.zip
- --------E20D265167F98506.mp3
- --------F53A522FF938F1F4.zip
- */
File过滤器
- package com.itlwc;
- import java.io.File;
- import java.io.FilenameFilter;
- public class IO {
- public static void main(String[] args) {
- File file = new File("d:\\文件夹");
- findJava1(file);
- System.out.println("-------------");
- findJava2(file);
- }
- // 使用原始方法过滤文件
- public static void findJava1(File file) {
- String[] str = file.list();
- for (String s : str) {
- if (s.endsWith(".java")) {
- System.out.println(s);
- }
- }
- }
- // 使用FilenameFilter过滤文件
- public static void findJava2(File file) {
- String[] str = file.list(new FilenameFilter() {
- public boolean accept(File dir, String name) {
- if (name.endsWith(".java"))
- return true;
- return false;
- }
- });
- for (String s : str) {
- System.out.println(s);
- }
- }
- }
IO流
- Java的流建立在4个抽象类的基础上
- InputStream,OutputStream,Reader,Writer
- InputStream和OutputStream是字节流
- Reader和Writer是字符流
- 一般的流都是单向的,java.io.RandomAccessFile类比较特殊,是一个双向的
- IO流分类
- 根据功能分为:
- 输入流(Input Stream)和输出流(Output Stream)
- 通常人站在程序的角度来判断流的方向
- 输入流只能读数据
- 输出流只能写数据
- 根据结构分为:
- 字节流(Byte Stream)和字符流(Character Stream)
- 字节流以字节为单位进行数据传输,用于处理字节和二进制对象
- 字符流以字符为单位进行数据传输,用于处理字符和字符串
- 根据数据流操作方式分为:
- 节点流(Node Stream)和过滤流(Filter Stream)
- 节点流是可以直接创建的流
- 过滤流是可以装饰节点流让节点流功能更强大,过滤流使用了装饰者模式
- 节点流和过滤流一般是配合使用
- 转换流
- 字节流和字符流之间的转化,一般字节流不方便操作,转换为字符流处理
FileOutputSteam/BufferedOutputStream写文件
- package com.itlwc;
- import java.io.BufferedOutputStream;
- import java.io.FileOutputStream;
- public class IO {
- // 输出流写入文件
- public void execute1() throws Exception {
- FileOutputStream fos = new FileOutputStream("D:\\文件夹\\a.txt", true);
- String str = "abcdefghigklmnopqrstuvwxyz";
- byte[] buf = str.getBytes();
- fos.write(buf);
- fos.close();
- }
- // 输出流带缓冲写入文件
- public void execute2() throws Exception {
- FileOutputStream fos = new FileOutputStream("D:\\文件夹\\a.txt", true);
- BufferedOutputStream bos = new BufferedOutputStream(fos);
- String str = "abcdefghigklmnopqrstuvwxyz";
- byte[] buf = str.getBytes();
- bos.write(buf);
- // 使用缓冲流一定要flush(),如果关闭流会自动flush()
- bos.close();
- }
- public static void main(String[] args) throws Exception {
- new IO().execute1();
- new IO().execute2();
- }
- }
FileInputSteam/BufferedInputStream读文件
- package com.itlwc;
- import java.io.BufferedInputStream;
- import java.io.FileInputStream;
- public class IO {
- // 输入流读取文件
- public void execute1() throws Exception {
- FileInputStream fis = new FileInputStream("D:\\文件夹\\a.txt");
- byte[] buf = new byte[1024];
- // 从输入流中读取一定数量的字节并将其存储在缓冲区数组b中
- int len = fis.read(buf);
- String str = "";
- while (len != -1) {
- // 构造一个新的String,方法是使用指定的字符集解码字节的指定子数组
- str = new String(buf, 0, len);
- len = fis.read();
- }
- System.out.print(str);
- fis.close();
- }
- // 输入流带缓冲读取文件
- public void execute2() throws Exception {
- FileInputStream fis = new FileInputStream("D:\\文件夹\\a.txt");
- BufferedInputStream bis = new BufferedInputStream(fis);
- byte[] buf = new byte[1024];
- int len = bis.read(buf);
- String str = "";
- while (len != -1) {
- str = new String(buf, 0, len);
- len = fis.read();
- }
- System.out.print(str);
- // 使用缓冲流一定要flush(),如果关闭流会自动flush()
- bis.close();
- }
- public static void main(String[] args) throws Exception {
- new IO().execute1();
- System.out.println();
- new IO().execute2();
- }
- }
- /*
- 打印结果:
- abcdefghigklmnopqrstuvwxyzabcdefghigklmnopqrstuvwxyz
- abcdefghigklmnopqrstuvwxyzabcdefghigklmnopqrstuvwxyz
- */
实现文件拷贝
- package com.itlwc;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- public class IOInputOutputStream {
- // 输入流输出流实现拷贝文件
- public void execute1() throws Exception {
- FileInputStream fis = new FileInputStream("D:\\文件夹\\a.txt");
- FileOutputStream fos = new FileOutputStream("D:\\文件夹\\b.txt",true);
- byte[] buf = new byte[1024];
- int len = 0;
- while (-1 != len) {
- fos.write(buf, 0, len);
- len = fis.read(buf, 0, buf.length);
- }
- fis.close();
- fos.close();
- }
- // 输入流输出流带缓冲实现拷贝文件
- public void execute2() throws Exception {
- FileInputStream fis = new FileInputStream("D:\\文件夹\\a.txt");
- BufferedInputStream bis = new BufferedInputStream(fis);
- FileOutputStream fos = new FileOutputStream("D:\\文件夹\\b.txt",true);
- BufferedOutputStream bos = new BufferedOutputStream(fos);
- byte[] buf = new byte[1024];
- int len = 0;
- while (-1 != len) {
- bos.write(buf, 0, len);
- len = bis.read(buf, 0, buf.length);
- }
- // 使用缓冲流一定要flush(),如果关闭流会自动flush()
- bis.close();
- bos.close();
- }
- }
DataOutputStream/DateInputStream读写数据
- package com.itlwc;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- public class IODateInputStream {
- public static void main(String[] args) throws Exception {
- DataOutputStream dos = new DataOutputStream(new FileOutputStream(
- "D:\\文件夹\\c.txt", true));
- byte b = 3;
- int i = 12;
- char c = 'a';
- float f = 3.3f;
- //这里并不是写入了一个3,而是写入了一个byte类型的3
- dos.writeByte(b);
- dos.writeInt(i);
- dos.writeChar(c);
- dos.writeFloat(f);
- dos.close();
- //读和写要保持一致
- DataInputStream dis = new DataInputStream(new FileInputStream(
- "D:\\文件夹\\c.txt"));
- System.out.println(dis.readByte());
- System.out.println(dis.readInt());
- System.out.println(dis.readChar());
- System.out.println(dis.readFloat());
- dis.close();
- }
- }
Writer写文件
- package com.itlwc;
- import java.io.BufferedWriter;
- import java.io.FileWriter;
- public class IO {
- // 不带缓存
- public void execute1() throws Exception {
- String str = "李文超,hello!";
- FileWriter fw = new FileWriter("D:\\a.txt", true);
- fw.write(str);
- // 必须关闭输出字节流,否则不能写入文件
- fw.close();
- }
- // 带缓存
- public void execute2() throws Exception {
- String str = "李文超,hello!";
- FileWriter fw = new FileWriter("D:\\a.txt", true);
- BufferedWriter bfw = new BufferedWriter(fw);
- bfw.write(str);
- // 必须关闭输出字节流,否则不能写入文件
- bfw.close();
- }
- public static void main(String[] args) throws Exception {
- new IO().execute1();
- new IO().execute2();
- }
- }
Reader读文件
- package com.itlwc;
- import java.io.BufferedReader;
- import java.io.FileReader;
- public class IO {
- public void execute1() throws Exception {
- FileReader fr = new FileReader("D:\\a.txt");
- char[] buf = new char[1024];
- int len = fr.read(buf);
- System.out.println(new String(buf, 0, len));
- fr.close();
- }
- public void execute2() throws Exception {
- FileReader fr = new FileReader("D:\\a.txt");
- BufferedReader br = new BufferedReader(fr);
- String str = br.readLine();
- System.out.println(str);
- br.close();
- }
- public static void main(String[] args) throws Exception {
- new IO().execute1();
- System.out.println();
- new IO().execute2();
- }
- }
InputStreamReader
- package com.itlwc;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- //控制台输入
- public class IO {
- public static void main(String[] args) throws Exception {
- InputStreamReader isr = new InputStreamReader(System.in);
- BufferedReader br = new BufferedReader(isr);
- String str = br.readLine();
- System.out.println(str);
- br.close();
- }
- }
RandomAccessFile
- 双向的流(随机访问文件类)
- 它不是派生于InputStream和OutputStream,而是实现了DataInput和DataOutput
- 它支持定位请求,可以在文件内部放置指针
- 有两个构造方法:
- RandomAccessFile(File fileObject,String access)
- RandomAccessFile(String fileName,String access)
- access都决定允许访问何种文件类型,如果是r可读,如果是rw可读可写
- RandomAccessFile案例说明
- 向文件中写3个雇员,然后按2,1,3的顺序读出
- 需要注意的是,要想按位置读出来,必须保证每条记录在文件中的具体位置,
- 假设name是8个字符,少于8个的补空格,大于8个的去掉多余的部分
- 由于年龄是int的,所以不管这个年龄多大,只要不超过int的范围,
- 在内存中都是占4个字节大小
RandomAccessFile案例
- package com.itlwc;
- import java.io.RandomAccessFile;
- class Employee {
- String name;
- int age;
- final static int LEN = 8;
- public Employee(String name, int age) {
- if (name.length() > LEN) {
- name = name.substring(0, 8);
- } else {
- while (name.length() < LEN) {
- name = name + "\u0000";
- }
- }
- this.name = name;
- this.age = age;
- }
- }
- public class Test {
- public static void main(String[] args) throws Exception {
- Employee e1 = new Employee("zhangsan", 23);
- Employee e2 = new Employee("lisi", 26);
- Employee e3 = new Employee("wangwu", 30);
- RandomAccessFile ra = new RandomAccessFile("d:\\employee.txt", "rw");
- ra.write(e1.name.getBytes());
- ra.writeInt(e1.age);
- ra.write(e2.name.getBytes());
- ra.writeInt(e2.age);
- ra.write(e3.name.getBytes());
- ra.writeInt(e3.age);
- ra.close();
- RandomAccessFile raf = new RandomAccessFile("d:\\employee.txt", "r");
- int len = 8;
- raf.skipBytes(12);// 跳过第1个雇员信息
- System.out.println("第二个雇员信息");
- String name = "";
- for (int i = 0; i < len; i++) {
- byte b = raf.readByte();
- char c = (char) b;
- name = name + c;
- }
- System.out.println("name: " + name);
- System.out.println("age: " + raf.readInt());
- raf.seek(0);// 将文件指针移动到文件开始位置
- System.out.println("第一个雇员信息");
- name = "";
- for (int i = 0; i < len; i++) {
- byte b = raf.readByte();
- char c = (char) b;
- name = name + c;
- }
- System.out.println("name: " + name);
- System.out.println("age: " + raf.readInt());
- raf.skipBytes(12);// 跳过第2个雇员信息
- System.out.println("第三个雇员信息");
- name = "";
- for (int i = 0; i < len; i++) {
- byte b = raf.readByte();
- char c = (char) b;
- name = name + c;
- }
- System.out.println("name: " + name);
- System.out.println("age: " + raf.readInt());
- raf.close();
- }
- }
- /*
- 打印结果:
- 第二个雇员信息
- name: lisi
- age: 26
- 第一个雇员信息
- name: zhangsan
- age: 23
- 第三个雇员信息
- name: wangwu
- age: 30
- */