JAVA学习笔记31(IO流)

1.IO流

1.文件流

​ *文件在程序中是以流的形式来操作的


2.常用文件操作

1.创建文件对象

1.new File(String pathname)

//根据路径构建一个File对象

java 复制代码
main()
{
	
}

public void create01() {
    String filePath = "e:\\news1.txt";
    File filePath = new File(filePath);
    
    try{
    	file.createNewFile();     
    } catch (IOException e){
        e.printStackTrace();
    }

}

2.new File(File ,String child)

//根据父目录文件+子路径构建

java 复制代码
public void create02() {
	File parentFile = new File("e:\\");
    String fileName = "new2.txt";
    //这里的file对象,在java程序中,只是一个对象
    //只有执行了createNewFile方法,才会真正的创建文件
    File file = new File(parentFile,fileName)
        
    try{
    	file.createNewFile();     
    } catch (IOException e){
        e.printStackTrace();
    }
}

3.new File(String parent , String child)

//根据父目录+子路径构建

java 复制代码
public void create03() {
    String parentPath = "e:\\";	//"\\"表示转义字符"\"
    String fileName = "news3.txt";
    File file = new File(parentPath, fileName);
    
    try{
    	file.createNewFile();     
    } catch (IOException e){
        e.printStackTrace();
    }
}

​ *createNewFile 创建新文件

2.获取文件信息

java 复制代码
public class test01 {
	public static void main(String[] args) {
 		       
    }
    //获取文件信息
    public void info() {
		//先创建文件对象
        File file = new File("e:\\news1.txt");
        
        //调用相应的方法,得到对应信息
    	System.out.println("文件名字=" + file.getName());
    	//getName、getAbsolutePath、length、exists、isFile、isDirectory
        System.out.println("文件绝对路径=" + file.getAbsolutePath());
        System.out.println("文件父级目录=" + file.getParent());
        System.out.println("文件大小(字节)=" + file.length());
        System.out.println("文件是否存在=" + file.exists());//T
        System.out.println("是不是一个文件=" + file.isFile());//T
        System.out.println("是不是一个目录=" + file.isDirectory());//T
}

3.目录的操作和文件删除

​ *mkdir创建一级目录、mkdirs创建多级目录、delete删除空目录或文件

java 复制代码
//判断d:\\news1.txt是否存在,如果存在就删除
@Test
public void m1() {
    String filePath = "d:\\news1.txt";
    File file = new File(filePath);
    if(file.exists()) {
        file.delete()
    } else {
        System.out.println("该文件不存在...");
    }
}

//判断目录D:\\demo02是否存在,如果存在就删除,否则提示不存在
//在java中,目录也被当做文件
@Test
public void m2() {
    String filePath = "D:\\demo02";
    File file = new File(filePath);
    if(file.exists()) {
        file.delete()
    } else {
        System.out.println("该文件不存在...");
    }
}

//判断目录D:\\demo\\a\\b\\c 是否存在,如果存在就提示存在,否则就创建
//在java中,目录也被当做文件
@Test
public void m3() {
    String directoryPath = "D:\\demo\\a\\b\\c";
    File file = new File(directoryPath);
    if(file.exists()) {
        System.out.println("该文件存在");
    } else {
        //创建多级目录,返回boolean值
        if(file.mkdirs()) {
            System.out.println(directoryPath + "创建成功");
        }
    }
}

3.IO流原理及流的分类

1.I/O是Input/Output的缩写,I/O技术用于处理数据传输,读/写文件,网络通讯

2.Java中,对于数据的输入/输出操作以"流(stream)"的方式进行

3.java.io包下提供了各种"流"类和接口,用以获取不同种类的数据,并通过方法输入或输出数据

4.输入input:读取外部数据(磁盘,光盘等存储设备的数据)到程序(内存)中

5.输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中

1.流的分类

1.输入流和输出流

1.按操作数据单位不同分为:字节流(8bit)【二进制文件】,字符流(按字符)【文本文件】

2.按数据流额流向不同分为:输入流,输出流

3.按流的角色的不同分为:节点流,处理流/包装流



1.InputStream

:字节输入流

​ *InputStream抽象类是所有类字节输入流的超类

​ *常用子类

1.FileInputStream:文件输入流

java 复制代码
@Test
//单个字节读取,效率低
public void readFile01() {
    String filePath = "e:\\hello.txt";
    int readData = 0;
     FileInputStream fileInputStream = null
    try {
        //创建FileInputStream对象,用于读取文件
        fileInputStream = new FileInputStream(filePath);
        //从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
        //如果返回-1,表示读取完毕
        while((readData = fileInputStream.read())!= -1) {
            System.out.print((char)readData);//转成char显示
        }
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        //关闭文件流,释放资源
    	fileInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//使用read(byte[] b)读取文件,提高效率
@Test
public void readFile02() {
    String filePath = "e:\\hello.txt";
    int readData = 0;
    //字节数组
    byte[] buf = new byte[8];//一次读取8个字节
    int readLen = 0;
    
    
     FileInputStream fileInputStream = null
    try {
        //创建FileInputStream对象,用于读取文件
        fileInputStream = new FileInputStream(filePath);
        //从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
        //如果返回-1,表示读取完毕
        //如果读取正常,返回实际读取的字节数
        while((readLen = fileInputStream.read(buf))!= -1) {
            System.out.print(new String(buf,0,readLen);
        }
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        //关闭文件流,释放资源
    	fileInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2.BufferedInputStream:缓冲字节输入流

3.ObjectInputStream:对象字节输入流

2.OutputStream

​ *FileOutputStream

java 复制代码
@Test
public void writeFile() {
    //创建FileOutputStream对象
    String filePath = "e:\\a.txt";
    FileOutputStream fileOutputStream = null;
    
    try {
        //1.new FileOutputStream(filePath)创建方式,当写入内容时,会覆盖原来的内容
        //2.new FileOutputStream(filePath , true)创建方式,当写入内容时,是追加到文件后面
        
        
        //得到FileOutputStream对象
        fileOutputStream = new FileOutputStream(filePath);
        //写入一个字节
        fileOutputStream.write('H');
        //写入字符串
        String str = "hello,world";
        //str.getBytes()可以把字符串->字节数组
        fileOutputStream.write(str.getBytes());
        //write(byte[] b ,int off,int len)将len字节从位于偏移量off的指定字节数组写入
        fileOutputStream.write(str.getBytes(), 0,str.length());
     	fileOutputStream.write(str.getBytes(), 0, 3);//只写入前3个字节
        
        
    } catch (IOException e) {
		e.printStackTrace();
    } finally {
        try {
			fileOutputStream.close()
        } catch (IOException e) {
        	e.printStackTrace();
        }
    }
}
3.FileReader和FileWriter介绍

​ *FileReader和FileWriter是字符流,即按照字符来操作io

​ *FileReader相关方法

1.new FileReader(File/String)

2.read:每次读取单个字符(汉字格式),返回该字符,如果到文件末尾返回-1

3.read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果文件末尾返回-1

​ *相关API

1.new String(char[]):将char[]转换为String

2.new String(char[], off, len):将char[]的指定部分转换成String

​ *FileWriter常用方法

1.new FileWriter(File/String):覆盖模式,相当于流的指针在首端

2.new FileWriter(File/String, true):追加模式,相当于流的指针在尾端

3.write(int):写入单个字符

4.write(char[]):写入指定数组的指定部分

5.write(char[], off ,len):写入指定数组的指定部分

6.write(String):写入整个字符串

7.write(String, off ,len):写入字符串的指定部分

​ *相关API

String类:toCharArray:将String转换成char[]

​ *注意

FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件

2.节点流和处理流

1.节点流可以从一个特定的数据源读写数据,如FileReader、FileWriter

2.处理流(也叫包装流)是"链接"在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,也更加灵活,如BufferedReader、BufferedWriter


1.BufferedReader

​ *只能处理字符,不能处理字节

java 复制代码
main()
{
    String filePath = "文件路径";
    BufferedReader bufferedReader = new BufferedReader(new FileReader(filepath,true));
    
    int readLen =0;
    String line;
    while((line = fileReader.readLine())!=null)
    {
 		System.out.println(line);       
    }
    
    //关闭流
    bufferedReader.close();
}
2.BufferedWriter

​ *只能处理字符,不能处理字节

java 复制代码
public class test01 {
	public static void main(String[] args) {
 		String filePath ="文件路径";
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
        bufferedWriter.write("Hello,韩顺平教育");
            bufferedWriter.newLine();//插入一个和系统相关的换行
    } 
    
    bufferedWriter.close();
}
3.BufferedInputStream
java 复制代码
public class test01 {
	public static void main(String[] args) {
 		String srcFilePath = "文件路径";
        String destFilePath = "目标路径";
        
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        
        try {
            bis = new BufferedInputStream(new FileInputStream(srcFilePath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
            
            //循环读取文件,斌写入到destFilePath
            byte[] buff = new byte[2024];
            int readLen = 0;
            
            while ((readLen = bis.read(buff))!= -1) {
                bos.write(buff, 0 ,readLen);
            }
            
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
			//关闭
            try {
				if(bis != null) bis.close();
                if(bos != null) bos.close();
            } catch {
                
            }
        }
    }           
}
4.BufferedOutputStream
3.对象处理流
1.ObjectOutputStream
java 复制代码
public class test01 {
	public static void main(String[] args) {
 		//创建流对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src\\data.dat"));
        //写入对象(序列化)
        oos.writeInt(100);
        oos.writeBoolean(true);
        oos.writeChar('a');
        oos.writeDouble(9.5);
        oos.writeUTF("呜呜");
        oos.writeObject(new Dog("阿迪王",10));//序列化对象
    
        //关闭
        oos.close()
    
    }           
}

//序列化对象需要继承Serializable接口
class Dog implements Serializable {
    
}
2.ObjectInputStream
java 复制代码
public class test01 {
	public static void main(String[] args) {
 		String filePath = "e:\\data.dat";
        
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
        
        //读取反序列化的顺序需要和保存数据(序列化)的顺序一致
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        Obejct dog = ois.readObject();
        System.out.println("运行类型=" + dog.getClass());
        System.out.println("dog信息=" + dog);
        
        
        //如果要调用Dog方法,需要向下转型
        Dog dog2 = (Dog)dog;
        dog2.getName();
        
        ois.close();
    }           
}

Serializable接口
class Dog implements Serializable {
    
}
3.注意事项
4.标准输入输出流
1.System.in
2.System.out
5.转换流

*字节-->字符

*处理纯文本数据时,使用字符流效率更高,并且有效解决了中文问题

*可以在使用时指定编码格式(比如: utf-8, gbk ,gb2312, ISO8859-1等)

1.InputStreamReader
java 复制代码
public class test01 {
	public static void main(String[] args) throws IOException {
 		String filePath = "文件路径";
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
        BufferedReader br = new BufferedReader(isr);
        
        String s = br.readLine();
        System.out.println(s);
        
        br.close()
    }           
}
2.OutputStreamWriter
java 复制代码
//将字节流FileOutputStream包装成字符流OutputStreamWriter,对文件写入(gbk格式)

//1.创建对象
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\a.txt"), "gbk");//以gbk方式写入

//2.写入
osw.write("hello,哈阿萨德");
//关闭
osw.close();
6.打印流
1.PrintStream
java 复制代码
public class test01 {
	public static void main(String[] args) {
 		PrintStream out = System.out;
        out.print("john,hello");
        //print底层调用的write,也可以直接调用write进行打印
        out.write("大萨达".getBytes());
        
        out.close();
        
        //修改打印流输出的位置
        System.setOut(new PrintStream("e:\\f1.txt"));
                out.print("john,hello");
    }           
}
2.PrintWriter
java 复制代码
public class test01 {
	public static void main(String[] args) {
 		PrintWriter printWriter = new PrintWriter(System.out);
            PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
        printWriter.print("hi,你好");
        printWriter.close();
    }           
}

4.拷贝图片

java 复制代码
@Test
public void copyPoto() {
	FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    String srcfilePath = "图片路径e:\\Kola.jpg";
    String destfilePath = "储存路径e:\\kola2.jpg";
    
    try {
        fileInputStream = new FileInputStream(srcfilePath);
        fileOutputStream = new FileOutputStream(destfilePath);
        //定义一个字节数组,提高读取效果
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = fileInputStream.read(buf)) != -1) {
            fileOutputStream.write(buf,0,readLen);//一定要用这个方法
        }
        System.out.println("拷贝OK")
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if(fileInputStream != null) {
             fileInputStream.close()   
            }
            if(fileOutputStream != null) {
				fileOutputStream.close();
            }
        } catch (IOException e) {
			e.printStackTrace();
        }
    }
}

​ *Buffered拷贝

java 复制代码
public class test01 {
	public static void main(String[] args) {
 		String srcFilePath ="文件路径";
        String desFilePath = "拷贝路径";
        BufferedReader br = null;
        BufferedWriter bw = null;
        String line;
        try {
            br = new BufferedReader(new FileReader(srcFilePath));
            bw = new BufferedWriter(new FileWriter(destFilePath));
            
            
            while((line = br.readLine()) != null) {
                bw.write(line);
                //readLine没有带换行符
                //插入换行符
                bw.newLine();
            }
        }
    }           
}
相关推荐
杨DaB8 分钟前
【SpringBoot】Swagger 接口工具
java·spring boot·后端·restful·swagger
YA3339 分钟前
java基础(九)sql基础及索引
java·开发语言·sql
桦说编程28 分钟前
方法一定要有返回值 \ o /
java·后端·函数式编程
小李是个程序1 小时前
登录与登录校验:Web安全核心解析
java·spring·web安全·jwt·cookie
David爱编程1 小时前
Java 创建线程的4种姿势,哪种才是企业级项目的最佳实践?
java·后端
hrrrrb2 小时前
【Java Web 快速入门】十一、Spring Boot 原理
java·前端·spring boot
Java微观世界2 小时前
Object核心类深度剖析
java·后端
MrSYJ2 小时前
为什么HttpSecurity会初始化创建两次
java·后端·程序员
hinotoyk2 小时前
TimeUnit源码分享
java
Include everything3 小时前
Rust学习笔记(三)|所有权机制 Ownership
笔记·学习·rust