个人java学习路线-IO流

io流介绍

java IO操作主要是指使用Java进行输出,输入操作,这些操作类都放在Java.io包中。
我们在学习io时掌握了解以下16个类即可:

文件专属:
java.io.FileInputStream
java.io.FileOutputStream
java.io.FileReader
java.io.FileWriter

转换流:(将字节转换成字符流)
java.io.InputStreamReader
java.io.OutputStreamWriter

缓冲流专属:
java.io.BuffereReader
java.io.BuffereWriter
java.io.BuffereInputStream
java.io.BuffereOutputStream

数据流专属:
java.io.DataInputStream
java.io.DataOutputStream

标准输出流:
java.io.PrintWriter
java.io.PrintStream

对象专属流:
java.io.ObjectInputStream
java.io.ObjectOutputStream

这个类名也是见名大概就知道意思了。这个没必要都说,很多都是差不多的,挑一些重点说说就行。

File

IO包中唯一与文件本身有关的类,创建文件和删除文件都在这个类中,所以先说说这个类。
1》先了解创建文件/目录

public class FileTest {
    public static void main(String[] args) {
        File file=null;
        file=new File("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\试用.txt");//""中填文件的绝对路径,\\双斜杠是为了转义,/也行
        System.out.println(file.exists());
        if (!file.exists()) {//如果试用.txt不存在,创建该文件
            try {
//                file.mkdir();//创建文件夹
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File file1=new File("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\a\\b\\c");
        if (!file1.exists()){//如果目录不存在创建目录
            file1.mkdirs();
        }
    }
}

运行后结果:
在这里插入图片描述
2》了解获取文件路径

public class FileTest2 {
    public static void main(String[] args) {
        File file=new File("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\试用.txt");
        String parentPath=file.getParent();
        System.out.println(parentPath);
        System.out.println(file.getAbsolutePath());
    }
}

输出结果:
在这里插入图片描述
可以看出两个方法的不同
3》了解File的一些方法

public class FileTest3 {
    public static void main(String[] args) {
        File file=new File("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\试用.txt");
        System.out.println(file.isDirectory());	//文件是目录吗
        System.out.println(file.isFile());		//是文件吗(普通文本)
        System.out.println(file.lastModified());//文件最后修改时间(毫秒)
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date(file.lastModified())));	//文件最后修改时间改为标准模式
        System.out.println(file.length());		//文件内字节长度,这个不同类型不一样,单个汉字长3,其他可以自己试。
    }
}

输出结果:
在这里插入图片描述
4》了解扫描目录

public class FileTest4 {
    public static void main(String[] args) {
        File file=new File("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt");
        File[] files=file.listFiles();
        for (File f:files) {
            System.out.println(f.getAbsolutePath());
        }
    }
}

输出结果:
在这里插入图片描述
目前了解这些就行

文件专属流

FileInputStream

1》先来看看读取字符

public class FileInputStreamTest {
    public static void main(String[] args) {
        FileInputStream fis=null;
        try {
            fis=new FileInputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\fileio.txt");//连接fileio.txt文件
            int readData= fis.read();//往后读一位
            System.out.println(readData);
            System.out.println(fis.read());//继续读
            System.out.println(fis.read());
            System.out.println(fis.read());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();	//关闭流,必须关闭
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

输出结果:
在这里插入图片描述
可见输出的是ASCII码
2》用循环读完整个txt

public class FileInputStreamTest2 {
    public static void main(String[] args) {
        FileInputStream fis=null;
        try {
            fis=new FileInputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\fileio.txt");
            int readData=0;
            while((readData= fis.read())!=-1){//read=-1代表没东西读了
                System.out.print(readData+" ");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

读出来的都是ASCII码
3》输出字符串

public class FileInputStreamTest3 {
    public static void main(String[] args) {
        FileInputStream fis=null;
        try {
            fis=new FileInputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\fileio.txt");
            byte[] bytes=new byte[8];//一次读8byte
            int readCount;
            while ((readCount= fis.read(bytes))!=-1){
                System.out.print(new String(bytes,0,readCount));
            };
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

输出结果:
在这里插入图片描述
乱码是因为读的不完整,把new byte[8]改大些就行比如new byte[1024],就不会有错误了。
4》文件.available()方法,直接返回文件大小。

public class FileInputStreamTest4 {
    public static void main(String[] args) {
        FileInputStream fis=null;
        try {
            fis=new FileInputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\fileio.txt");
            byte[] bytes=new byte[fis.available()];
            int readCount= fis.read(bytes);
            System.out.println(new String(bytes));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

注意:4》不常用,大文件读取没那么大的空间存数组,一般用3》读几m(x10241024)就行

FileOutputStream

public class FileOutputStreamTest {
    public static void main(String[] args) {
        FileOutputStream fos=null;
        try {
        //            fos=new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\fileiooutput.txt",true);这个true代表是再txt原有内容上继续写入,默认是重写。
            fos=new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\fileiooutput.txt");
            String s="学习真开心啊!\n";
            byte[] bytes=s.getBytes();//把s存入字节数组中
            fos.write(bytes);			//写入
            fos.flush();				//刷新,必须步骤
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

输出结果:
在这里插入图片描述

缓冲流

该流使用需转换。
文件.readLine()可以读一行,同样文件.write()也可以写入一行

public class BufferedReaderTest {
    public static void main(String[] args){
        FileReader reader= null;
        BufferedReader br=null;
        try {
            reader = new FileReader("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\fileio.txt");//节点流
            br=new BufferedReader(reader);//包装流,处理流
             String s=null;
            while ((s=br.readLine())!=null){
                System.out.println(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

在使用BufferedReader时需要用转换流转换。

br=new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\fileio.txt")));

这个简单了解就行。

数据流

这个容易读出错,所以先写再读,可以当一种密码了,如果不知道写入顺序,很难读出来。
写入:

public class DataOutputStreamTest {
    public static void main(String[] args) {
        DataOutputStream dos=null;
        try {
            dos=new DataOutputStream(new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\试用.txt"));
            int i=10;
            boolean b=true;
            double d=1.2;
            char c='d';
            dos.writeInt(i);
            dos.writeBoolean(b);
            dos.writeDouble(d);
            dos.writeChar(c);
            dos.writeChars("how old are you");
            dos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

txt中保存的直接看时乱码的:
在这里插入图片描述
接下来就是读取了:

public class DataInputStreamTest {
    public static void main(String[] args) {
        DataInputStream dis=null;
        try {
            dis=new DataInputStream(new FileInputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\试用.txt"));
            System.out.print(dis.readInt());
            System.out.print(dis.readBoolean());
            System.out.print(dis.readDouble());
            System.out.print(dis.readChar());
            System.out.print(dis.readLine());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

输出结果:
在这里插入图片描述
简单了解就行。

标准输出流

1》
这个可以改我们的老朋友Hello World了,这个操作相关就行System.out,直接看代码:

public class PrintStreamTest {
    public static void main(String[] args) {
        PrintStream ps=System.out;
        ps.println(123);		//这里就相当于System.out.println();了
        ps.println("hello");
        try {
            System.setOut(new PrintStream(new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\试用.txt")));//设置输出口,本该打印到控制台的内容打印到txt文件。
            System.out.println("welcome");
            System.out.println("earth");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

输出结果:
在这里插入图片描述
还是很有意思的。
2》
我们来尝试往txt里输入时间:
设定一个方法,先将System.out输出口设为txt,再正常打印时间。

public class PrintStreamTest2 {
    public static void log(String s){
        try {
            System.setOut(new PrintStream(new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\试用.txt")));
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date())+":"+s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

调用方法:

public class Test2Test {
    public static void main(String[] args) {
        PrintStreamTest2.log("测试时间");
    }
}

查看txt:
在这里插入图片描述
简单了解一下。

对象专属流

1》
和上面都一样拉,不过改成对象了。
学生类:

public class Student implements Serializable {
    private int no;
    private String name;
    public Student() {
    }
    public Student(int no, String name) {
        this.no = no;
        this.name = name;
    }
    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return no == student.no &&
                Objects.equals(name, student.name);
    }
    @Override
    public int hashCode() {
        return Objects.hash(no, name);
    }
    @Override
    public String toString() {
        return "Student{" +
                "no=" + no +
                ", name='" + name + '\'' +
                '}';
    }
}

写入类:

public class ObjectStreamTest {
    public static void main(String[] args) {
        Student stu=new Student(1111,"张三");
        ObjectOutputStream oos=null;
        try {
            oos=new ObjectOutputStream(new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\oos.txt"));
            oos.writeObject(stu);
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

查看Txt:
在这里插入图片描述
然后就是读取了:

public class ObjectInputStreamTest {
    public static void main(String[] args) {
        ObjectInputStream ois=null;
        try {
            ois=new ObjectInputStream(new FileInputStream("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\oos.txt"));
            System.out.println(ois.readObject());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

读取结果:
在这里插入图片描述
2》集合当然也可以,感兴趣自己尝试。

补充IoAndProperties

这个对以后的学习很重要,重要再Properties这个属性文件,往后我们可能经常会写xx.properties文件。先看看txt里内容:
在这里插入图片描述
然后看代码:

public class Test {
    public static void main(String[] args) {
        FileReader reader=null;
        try {
            reader=new FileReader("C:\\Users\\Lenovo\\Desktop\\java\\1javaio控制的txt\\ioAndProperties.txt");
            Properties pro=new Properties();
            pro.load(reader);
            System.out.println(pro.getProperty("username"));
            System.out.println(pro.getProperty("password"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

再看看运行输出:
在这里插入图片描述
是不是有集合那感觉了,这个很有用。

拷贝目录

自己做个复制文件出来,直接给代码,感兴趣自己看:
这个容易出错,即目录是有多层的,需要进入扫描拷贝,容易错位啥的,这个改了挺久,应该没啥大问题,反正是玩玩。

public class 拷贝目录修改 {
    public static void main(String[] args) {
        File srcFile=new File("I:\\yule\\ce修改器");		//需拷贝文件
        File destFile=new File("C:\\Users\\Lenovo\\Desktop");//拷贝地点
        copyDir(srcFile,destFile);
    }
    /**
     * 拷贝文件
     * @param srcFile 拷贝源
     * @param destFile 拷贝目标
     */
    private static void copyDir(File srcFile, File destFile) {
        String srcStr=srcFile.getAbsolutePath();
        String destStr=destFile.getAbsolutePath()+"\\"+srcFile.getName()+"javaio复制";
        copyDirStart(srcFile,srcStr,destStr);
    }

    private static void copyDirStart(File srcFile, String srcStr,String destStr) {
        if (srcFile.isFile()){
            copyFile(srcFile,srcStr,destStr);
            return;
        }
        if (srcFile.isDirectory()){
            File[] files=srcFile.listFiles();
            if((files != null ? files.length : 0) !=0){
                for (File sonFile:files) {
                    if (sonFile.isFile()){
                        copyFile(sonFile,srcStr,destStr);
                    }else {
                        File newFile=new File(sonFile.getAbsolutePath().replace(srcStr,destStr));
                        if (!newFile.exists()){
                            newFile.mkdirs();
                        }
                        copyDirStart(sonFile,srcStr,destStr);
                    }
                }
            }
        }
    }

    private static void copyFile(File srcFile,String srcStr,String destStr) {
        FileInputStream in=null;
        FileOutputStream out=null;
        try {
            in=new FileInputStream(srcFile);
            out=new FileOutputStream(srcFile.getAbsolutePath().replace(srcStr,destStr));
            byte[] bytes=new byte[50*1024*1024];
            int readCount=0;
            while ((readCount=in.read(bytes))!=-1){
                out.write(bytes,0,readCount);
            }
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值