JAVASE入门十二脚-file,IO流

时间:2025-01-31 12:48:40

File文件

package IO_Demo;

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

public class File_Demo {
    public static void main(String[] args)  {
        File file=new File("src/abc.txt");
        //创建文件
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        file.canExecute();
        file.canRead();
        file.canWrite();
        //当前文件是否存在
        System.out.println( file.exists());;
        System.out.println(file.getName());
        //获取文件的绝对路径
        System.out.println(file.getAbsoluteFile());
        //获取文件的父路径名称,如果文件只包含文件的路径名称,则显示空
        System.out.println(file.getParent());
        try {//返回文件的绝对路径文件格式
            System.out.println(file.getCanonicalFile());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //文件分隔符
        System.out.println(File.separator);
        File file2=new File("c:/");
        System.out.println(file2.getAbsoluteFile());
        System.out.println(file2.isDirectory());
        System.out.println(file2.isFile());

        String[] list = file2.list();
        for(String str:list){
            System.out.println(list.toString());
        }
        System.out.println("-------------------");
        File[] files = file2.listFiles();
        for(File f:files ){
            System.out.println(f);
            System.out.println(f.getAbsoluteFile());

        }
        System.out.println("----------------------");
        //打印当前文件系统 的盘符
        File[] files1 = File.listRoots();
        for(int i=0;i<files1.length;i++){
            System.out.println(files1[i]);
        }
        //创建单机目录和多级目录
       /* file2.mkdir();
        file2.mkdirs();
        */



    }
}

 流

 在java中需要读写文件中的数据的话,需要使用流的概念
流表示从一个文件将数据返送到另一个文件,包含一个流向的问题
最终需要选择一个参照物:当前程序作为参照物
从一个文件中取数据到程序叫做输入流
从程序输出数据到另一个文件叫做输出流

注意:当编写IO流的程序的时候一定要注意关闭流
步骤:
1、选择合适的IO流对象
2、创建对象
3、传输数据
4、关闭流对象

package IO_Demo;

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

public class StreamDemo4 {
    public static void main(String[] args) {
        InputStream inputStream = null;

        try {
            inputStream = new FileInputStream("abc.txt");
            int length = 0;
            //添加缓冲区的方式来进行读取,每次会将数据添加到缓冲区中,当缓冲区满了之后,一次读取,而不是每一个字节进行读取

            byte[] buffer = new byte[1024];
            while ((length = inputStream.read(buffer)) != -1) {
                System.out.println(new String(buffer, 0, length));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
package OutputstreamDemo;

import java.io.*;

public class OutputStreamDemo {
    public static void main(String[] args) {
        File file=new File("aaa.txt");
        OutputStream outputStream=null;
        try {
            outputStream=new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            outputStream.write(99);
            outputStream.write("\tbbbb".getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
       finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


    }
}

package Reader_Wirter;

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

public class ReaderDemo {
    public static void main(String[] args) {
        Reader reader=null;
        try {
            reader=new FileReader("abc.txt");
            int read=0;
            while (true){
                try {
                    if (!((read=reader.read())!=-1)) break;
                    System.out.println((char)read);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
//            try {
//                System.out.println((char)reader.read());
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
package Reader_Wirter;

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

public class ReaderDemo2 {
    public static void main(String[] args) {
        Reader reader=null;
        try {
            reader=new FileReader("abc.txt");
            char[] chars=new char[1024];
            int length=0;
            while (true){
                try {
                    if ((length=reader.read(chars))!=-1){
                    System.out.println(new String(chars,0,length));}
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }


            }
//            try {
//                System.out.println((char)reader.read());
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 传入文字

package Reader_Wirter;

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

public class WirterDemo {
    public static void main(String[] args) {
        File file=new File("wirte.txt");
        Writer writer=null;
        try {
            writer=new FileWriter(file);
            writer.write("大大大");
            writer.write("hahhaha");
            writer.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

 复制图片

package Reader_Wirter;

import java.io.*;

public class CopyDemo {
    public static void main(String[] args) {
        FileInputStream fileInputStream=null;
        FileOutputStream fileOutputStream=null;
        try {
            fileInputStream=new FileInputStream("1.jpg");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        try {
            fileOutputStream=new FileOutputStream("2.jpg");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        int length=0;
        byte[] bytes=new byte[1024];
        while (true){
            try {
                if (!((length=fileInputStream.read(bytes))!=-1)) break;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
               fileOutputStream.write(bytes);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}

什么时候需要加flush,什么时候不加flush
最保险的方式,在输出流关闭之前每次都加flush,然后再关闭
当某一个输出流对象中带有缓冲区的时候,就需要进行flush\

字符读取,作为0到65535(0x00-0xfff)范围内的整数,如果已经达到流的末尾,则为-1

inputstreamreader----outputstreamwriter

package Reader_Wirter;

import java.io.*;

public class FileOutputStreamDemo {
    public static void main(String[] args) {
        FileOutputStream fileOutputStream=null;
        OutputStreamWriter outputStreamWriter=null;
        try {
            fileOutputStream=new FileOutputStream("abc.txt");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        outputStreamWriter=new OutputStreamWriter(fileOutputStream);
        try {
            outputStreamWriter.write("5555");
            outputStreamWriter.write("abcdegg",0,5);
            outputStreamWriter.write("大虾");
            outputStreamWriter.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
//与创建时间进行逆序关闭
            try {
                outputStreamWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

package Reader_Wirter;

import java.io.*;

public class InputStreamReaderDemo {
    public static void main(String[] args) {
        File file=new File("abc.txt");
        InputStream inputStream=null;
        InputStreamReader inputStreamReader=null;
        try {
            inputStream=new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        inputStreamReader=new InputStreamReader(inputStream);
        char[] buffer=new char[1024];
        int length=0;
        while(true){
            try {
                if ((length=inputStreamReader.read(buffer))!=-1)
                    System.out.println(new String(buffer,0,length));break;
            } catch (IOException e) {
                throw new RuntimeException(e);

            }finally {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }
    }
}

byteArrayinputStream----byteArrayoutputStream

package Reader_Wirter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteoutputStreamDemo {
    public static void main(String[] args) {
        ByteArrayOutputStream byteArrayOutputStream=null;
        byteArrayOutputStream=new ByteArrayOutputStream();
        byteArrayOutputStream.write(123);
        try {
            byteArrayOutputStream.write("www.baidu.com".getBytes());
            System.out.println(byteArrayOutputStream.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
package Reader_Wirter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteoutputStreamDemo {
    public static void main(String[] args) {
        ByteArrayOutputStream byteArrayOutputStream=null;
        byteArrayOutputStream=new ByteArrayOutputStream();
        byteArrayOutputStream.write(123);
        try {
            byteArrayOutputStream.write("www.baidu.com".getBytes());
            System.out.println(byteArrayOutputStream.toString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}

1、如果需要将对象通过io流进行传输,那么必须要实现序列化接口
2、当前类中必须声明一个serialVersionUID的值,值为多少无所谓,但是要有
3、transient:使用此关键字修饰的变量,在进行序列化的时候。不会被序列化

package ObjectStreamDemo;


import java.io.Serializable;

public class Person implements Serializable {
    long SerializableUID=1L;
    private int id;
    private String name;
    private int pwd;

    public Person(){

    }

    public Person(int pwd, String name, int id) {
        this.pwd = pwd;
        this.name = name;
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPwd() {
        return pwd;
    }

    public void setPwd(int pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd=" + pwd +
                '}';
    }
}



package ObjectStreamDemo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class OutputStreamobjectDemo {
    public static void main(String[] args) {
        FileOutputStream fileOutputStream=null;
        ObjectOutputStream objectOutputStream=null;
        try {
            fileOutputStream=new FileOutputStream("abc.txt");
            objectOutputStream=new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeUTF("www.baidu.com");
            objectOutputStream.writeObject(new Person(13,"大虾",55664));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}



package ObjectStreamDemo;

import java.io.*;

public class InputStreamobjectDemo {
    public static void main(String[] args) {
        FileInputStream fileInputStream=null;
        ObjectInputStream objectInputStream=null;
        try {
           fileInputStream=new FileInputStream("abc.txt");
             objectInputStream=new ObjectInputStream(fileInputStream);
             objectInputStream.readUTF();
            System.out.println(objectInputStream.read());
            try {
                Object object=objectInputStream.readObject();
                if(object instanceof Person){
                    Person p=(Person) object;
                    System.out.println(p);
                }
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

//            try {
//                Person person=(Person) objectInputStream.readObject();
//            } catch (ClassNotFoundException e) {
//                throw new RuntimeException(e);
//            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                objectInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}