Java-IO篇

Java-IO流

IO流定义

  • File类用来描述一个文件或者目录,通过File对象可以读取文件或者目录的属性数据,如果需要读取文件的内容数据,需要使用IO技术。
  • IO流分类:
    • 按照数据流向分类:输入流和输出流(以程序为标准)
    • 按照处理单位分类:字节流和字符流。
      • 字节流:读取的是文件中不经任何处理的二进制数据
      • 字符流:字符流读取的数据以字符为单位,字符流也是读取文件中的二进制数据,不过会把二进制数据转化为字符。(字符流 = 字节流+解码)
    • 按照处理的功能位置划分:节点流(Inpuestream和OutStream)和处理流(BufferedInputStream和BufferedOutputStream)。

File类

  • File常用使用方法:

    package file;
    
    import java.io.File;
    import java.io.IOException;
    
    public class UseFile {
    
        public static void main(String[] args) {
            //创建File对象
            File file = new File("src/a.txt");
            //判断文件是否存在,如果不存在,创建文件
            new UseFile().createFile(file);
            //删除文件
            //new UseFile().deleteFile(file);
            //获取文件属性
            new UseFile().getFileProperty(file);
            //判断是文件还是目录
            new UseFile().judgeFileOrDir(file);
            //列出目录下的所有文件
            //new UseFile().listFile();
            //修改文件名称
            new UseFile().updateFileName(file);
    
        }
    
        public void createFile(File file){
            //文件不存在,创建文件
            if(!file.exists()){
                try {
                   if(file.createNewFile()){
                       System.out.println("文件创建成功");
                   }
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
            }
            else{
                System.out.println("文件已存在,创建失败");
            }
        }
    
        //file.deleteOnExit()--等待JVM退出后,在删除文件
        public void deleteFile(File file){
            if(file.exists()){
                if(file.delete()){
                    System.out.println("文件删除成功");
                }
            }
            else{
                System.out.println("文件不存在");
            }
        }
    
        public void getFileProperty(File file){
            //获取文件名
            String fileName = file.getName();
            System.out.println(fileName);
            //获取父文件名
            String name = file.getParent();
            System.out.println(name);
            //获取相对路径
            String relaPath = file.getPath();
            System.out.println(relaPath);
            //获取绝对路径
            String absoPath = file.getAbsolutePath();
            System.out.println(absoPath);
        }
    
        public void judgeFileOrDir(File file){
            if(file.isFile()){
                System.out.println("文件");
            }
            if(file.isDirectory()){
                System.out.println("目录");
            }
    
        }
    
        public void listFile( ){
            File file = new File("E:\\Java Project\\Java\\File\\res");
            //当前目录下的所有文件或目录
            File[] files = file.listFiles();
            for (File file1 : files) {
                if(file1.isDirectory()){
                    System.out.println("目录:"+file1.getName());
                }
                else{
                    System.out.println("文件:"+file1.getName());
                }
            }
    
        }
    
        public void updateFileName(File file){
    
            file.renameTo(new File("src/b.txt"));
        }
    
    }
    

FileInputStream类

  • InputStream类是所有输入字节流的基类 抽象类。FileInputStream类读取文件的输入字节流。

  • 使用FileIInputStream类读取文件数据的步骤:

    • 找到目标文件
    • 建立数据输入通道
    • 读取文件数据:read()
    • 关闭输入流

FileOutputStream类

  • 使用FileIOutputStream类读取文件数据的步骤:

    • 找到要写入的目的文件
    • 准备写入的字节数据
    • 数据写入到文件中:write()
    • 关闭输出流
  • 将一个文件数据写入到另一个文件中

    package file;
    
    import java.io.*;
    
    public class ReadFile {
    
        public static void main(String[] args) {
    
            String path = "src/file/b.txt";
            String desPath = "src/file/c.txt";
            ReadFile file = new ReadFile();
            String data = file.readFile(path);
            file.writeFile(desPath,data);
        }
    
        //读取文件中的数据
        public String readFile(String path){
            //定义输入流
            FileInputStream inputStream = null;
            int length = -1;
            String data = "";
            try {
                inputStream = new FileInputStream(path);
                //每次处理1024字节数据
                byte byteArray[] = new byte[1024];
                while( (length = inputStream.read(byteArray)) != -1){
                    data = data + new String(byteArray,0,length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    //关闭资源
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return data;
        }
    
        //将数据写入文件中
        public  void writeFile(String desPath,String data){
            FileOutputStream outputStream = null;
            try {
    
                //定义文件输出流,以追加的形式写入到目标文件中
                outputStream = new FileOutputStream(desPath,true);
                //将数据字符串转换为字节数组
                byte byteData[] = data.getBytes();
                outputStream.write(byteData);
                //清除缓冲区
                outputStream.flush();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

处理流:文件的读取和写入

BufferedInputStream 和 BufferedOutputStream : InputStream---->BufferedInputStream ------> BufferedOutputStream---->Outputstream

package file;

import java.io.*;

public class bufferStream {
    public static void main(String[] args) {
        try {
            int length = -1;
            //定义缓冲输入流和缓冲输出流
            FileInputStream inputStream = new FileInputStream("src/file/b.txt");
            BufferedInputStream bInputStream =new BufferedInputStream(inputStream);
            FileOutputStream outputStream = new FileOutputStream("src/file/c.txt");
            BufferedOutputStream bOutputStream =new BufferedOutputStream(outputStream);
            
            while((length = bInputStream.read())!=-1){
                System.out.println(length);
                bOutputStream.write(length);
            }
            //清空缓冲区
            bOutputStream.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Charset:字符集

package file;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class charSetTest {
    public static void main(String[] args) {
        String str = "adsd你";
        //获取默认字符集
        System.out.println(Charset.defaultCharset());
        //获取所有支持的字符集
        System.out.println(Charset.availableCharsets());
        try {
            byte bytes[] = str.getBytes("gbk");
        //str.getBytes(Charset.forName("gbk"));
            System.out.println(new String(bytes));
            System.out.println(new String(bytes,"gbk"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

字符流(以字符为单位进行读写)

  • 加入缓冲机制读写文件:Reader---->BufferedReader---->BufferedWriter---->Writer

    package file;
    
    import java.io.*;
    
    public class readChar {
        public static void main(String[] args) {
            String src = "src/file/b.txt";
            String des = "src/file/c.txt";
            readChar read = new readChar();
            read.readWrite(src,des);
        }
    
        //以字符的形式,将一个文件中的数据写入到另一个文件中去
        public void readWrite(String src,String des){
            BufferedReader bufferReader = null;
            BufferedWriter bufferedWriter = null;
    
            int length = -1;
            try {
                //定义Reader和Writer以及其缓冲类
                Reader reader = new FileReader(src);
                Writer writer = new FileWriter(des);
                bufferReader = new BufferedReader(reader);
                bufferedWriter = new BufferedWriter(writer);
                //开始读写数据
                while((length = bufferReader.read())!=-1){
                    bufferedWriter.write(length);
                }
                bufferedWriter.flush();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            finally {
    
    
            }
        }
    }
    

字节流转换为字符流

  • 应用场景:一个GBK文件转换为UTF-8文件

  • InputStream---->InputStreamReader---->BufferedReader---->BufferedWriter---->OutputStreamWriter---->OutputStream

    package file;
    import java.io.*;
    
    public class ByteToChar {
        public static void main(String[] args) {
    //        new ByteToChar().writeGBK("src/file/GBK.txt");
            new ByteToChar().gbkToUTF("src/file/GBK.txt","src/file/UTF-8.txt");
        }
        //将GBK格式的数据写入GBK文件
        public void writeGBK(String path){
            String str = "昨天、今天、明天";
            OutputStream out = null;
            try {
                byte bytes[] = str.getBytes("GBK");
                out = new FileOutputStream(path);
                out.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //将GBK编码的文件转换为UTF-8
    public void gbkToUTF(String src,String des){
        //输入流
        InputStream input = null;
        //处理流
        InputStreamReader reader = null;
        //缓冲字符流
        BufferedReader bufferReader = null;
         //输出流
        OutputStream output = null;
        //处理流
        OutputStreamWriter writer = null;
        //缓冲字符流
        BufferedWriter bufferWriter = null;
        int length = -1;
        try{
            input = new FileInputStream(src);
            //以GBK解码文件
            reader = new InputStreamReader(input,"GBK");
            bufferReader = new BufferedReader(reader);
    
            output = new FileOutputStream(des);
            //写入数据,默认格式为UTF-8
            writer = new OutputStreamWriter(output);
            bufferWriter = new BufferedWriter(writer);
            while((length = bufferReader.read())!=-1)
            {
                 bufferWriter.write(length);
            }
        }
        catch(IOException e){
            e.printStackTrace();
        }
        finally {
            try {
                bufferReader.close();
                bufferWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
    

对象流:ObjectStrem

  • 序列化:内存---->磁盘

    反序列化:磁盘---->内存

  • traisent修饰类中的属性,表示该属性不序列化

  • 类继承Serializable 接口,才能序列化。同时定义serialVersionUID,当类中的属性发生变化时,可以保证同步。

  • 类中的所有类属性,都要继承Serializable 接口。

package file;

import java.io.*;

public class ObjectStremTest {

    public static void main(String[] args) {
        String desPath = "src/file/save_class.txt";
//        new ObjectStremTest().writeObject(desPath);
        new ObjectStremTest().readObject(desPath);
    }

    //向文件中写对象
    public void writeObject(String desPath){
        ObjectOutputStream object = null;
        try {
            //定义对象流
            OutputStream output = new FileOutputStream(desPath);
            object = new ObjectOutputStream(output);
            object.writeObject(new Person("小明",13,"男"));
            object.flush();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                object.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    //从文件中读对象
    public void readObject(String src)
    {
        //定义对象输入流
        ObjectInputStream inputObject = null;
        try {
            InputStream input = new FileInputStream(src);
            inputObject = new ObjectInputStream(input);
            Person person = (Person) inputObject.readObject();
            System.out.println("姓名:"+person.getName()+"\t年龄:"+person.getAge()+"\t性别:"+person.getSex()+"\t地址:"+person.getAddress());
        }
        catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Java NIO

  • NIO和IO的最大区别:IO是面向流的,NIO是面向缓冲区的。IO流是阻塞的,NIO是非阻塞模式。
Files.createFile(Path.get(path))   ---->创建文件
Files.createDirectories(Path.get(path))   ---->创建目录
Files.move(Path.get(path),Path.get(path1))   --->剪切并改名
Files.delete(Path.get(path))  ---->删除文件
Files.copy(Path.get(path),Path.get(path1))   --->拷贝
Files.readAllByte(Paths.get(path))  ---- >读取文件中的内容 
Files.readAllLines(Paths.get(path))  ---->将文件内容以行的方式读出
Files.Writer(Paths.get(path),"sds".getBytes(字符集))   ---->向文件中写入数据
Files.Writer(Paths.get(path),"\nsds".getBytes(字符集),StandardOpenOption.APPEND)   ---->以追加的方式向文件中写入数据
  • Path
Path path1 = Paths.get("C:/kgc/eclipse");
Path path2 = Paths.get("C;/kgc/eclipse","eclipse.ini");
Path path3 = Paths.get("C:/","kgc/","eclipse");
  • RandomAccessFile读写文件
package file;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileTest {

    public static void main(String[] args) {
      new RandomAccessFileTest().readWriteFile("src/file/b.txt","src/file/d.txt");

    }

    //读文件
    public void readWriteFile(String src,String des){
        int length = -1;
        byte[] bytes = new byte[1024];
        try {
            //定义RandomAccessFile
            RandomAccessFile ranAccFile1 = new RandomAccessFile(src,"rw");
            RandomAccessFile ranAccFile2 = new RandomAccessFile(des,"rw");
            while ((length = ranAccFile1.read(bytes))!=-1){
//                System.out.println(new String(bytes,0,length));
                  ranAccFile2.write(bytes,0,length);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
  • commons-io:获取文件的扩展名、文件名、判断文件是否是以某某后缀名结尾、计算文件大小

  • properties :三种方式读取properties文件

    • jdk方式
    • spring的封装方式
    • Hutool的封装 方式
    package file;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    public class PropertiesTest {
        public static void main(String[] args) {
    //       String src = "src/resources/properties/db.properties";
             new PropertiesTest().readProperties();
        }
    
        /**
         * 方式一:jdk方式
         */ //加载输入流
        public void readProperties()
        {
            //通过类加载器的方式获取属性的输入流
            InputStream input = PropertiesTest.class.getClassLoader().getResourceAsStream("db.properties");
            //创建Properties
            Properties properties = new Properties();
            try {
                //加载输入流
                properties.load(input);
                //通过属性,获取属性值
                System.out.println("用户名:"+properties.getProperty("user"));
                System.out.println("密  码:"+properties.getProperty("pwd"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
         //spring方式
         Properties properties = PropertiesLoadUtils.loadAllProperties(db.properties);
         try {
                //通过属性,获取属性值
                System.out.println("用户名:"+properties.getProperty("user"));
                System.out.println("密  码:"+properties.getProperty("pwd"));
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        /**
         * 方式二:引入Hutool包
         */
        public void hutool()
        {
            Props props = new Props("db.properties");
            //通过属性,获取属性值
            System.out.println("用户名:"+props.getProperty("user"));
            System.out.println("密  码:"+props.getProperty("pwd"));
    
        }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值