Java高级---I/O

Java高级—I/O

在这里插入图片描述
实际使用的流:

字节流 字符流 转换流 缓冲流 二进制流 对象流
FileInputStream FileReader InputStreamReader BufferedReader DataInputStream ObjectInputStream
FileOutputStream FileWriter OutputStreamWriter BufferedWriter DataOutputStream ObjectOutputStream

一、文件的创建

File file  = new File("D:\\soft\\ApiProject\\src\\IO20210129\\Test\\test.txt");	//文件路径

二、File的主要方法

1、创建:
createNewFile() 在指定位置创建一个空文件,成功就返回true,如果已存在就不创建,然后返回false。
mkdir() 在指定位置创建一个单级文件夹。
mkdirs() 在指定位置创建一个多级文件夹。
renameTo(File dest) 如果目标文件与源文件是在同一个路径下,那么renameTo的作用是重命名, 如果目标文件与源文件不是在同一个路径下,那么renameTo的作用就是剪切,而且还不能操作文件夹。

2、删除:
delete() 删除文件或者一个空文件夹,不能删除非空文件夹,马上删除文件,返回一个布尔值。
deleteOnExit() jvm退出时删除文件或者文件夹,用于删除临时文件,无返回值。

3、判断:
exists() 文件或文件夹是否存在。
isFile() 是否是一个文件,如果不存在,则始终为false。
isDirectory() 是否是一个目录,如果不存在,则始终为false。
isHidden() 是否是一个隐藏的文件或是否是隐藏的目录。
isAbsolute() 测试此抽象路径名是否为绝对路径名。

4、获取:
getName() 获取文件或文件夹的名称,不包含上级路径。
getAbsolutePath() 获取文件的绝对路径,与文件是否存在没关系
length() 获取文件的大小(字节数),如果文件不存在则返回0L,如果是文件夹也返回0L。
getParent() 返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回null。
lastModified() 获取最后一次被修改的时间。

5、文件夹相关:
static File[] listRoots()列出所有的根目录(Window中就是所有系统的盘符)
list() 返回目录下的文件或者目录名,包含隐藏文件。对于文件这样操作会返回null。
listFiles() 返回目录下的文件或者目录对象(File类实例),包含隐藏文件。对于文件这样操作会返回null。
list(FilenameFilter filter) 返回指定当前目录中符合过滤条件的子文件或子目录。对于文件这样操作会返回null。
listFiles(FilenameFilter filter) 返回指定当前目录中符合过滤条件的子文件或子目录。对于文件这样操作会返回null。

三、文件的输入与输出

1、最基本的输入输出
输入

File file = new File("D:\\soft\\ApiProject\\src\\IO20210129\\Test2\\aa.txt");
//打开文件输入流
FileInputStream fis = new FileInputStream(file);
int temp = 0;      				 //临时存储读取的字符
while ((temp=fis.read())!=-1){	//直到读到文件结束
    System.out.print((char) temp);
}
//关闭
fis.close();

结果显示
aa.txt里面的内容:
在这里插入图片描述
控制台输出的内容:
在这里插入图片描述
这里乱码是因为文件的字符编码格式问题,等我们先写在读就不会出现这种问题。
【注意:UTF-8中汉字一般占3位】

2、字节流输入输出

输入

File file = new File("D:\\soft\\ApiProject\\src\\IO20210129\\Test2\\aa.txt");
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[fis.available()];
fis.read(b);
String s = new String(b);
System.out.println(s);
fis.close();

输出

File file = new File("D:\\soft\\ApiProject\\src\\IO20210129\\Test2\\b.txt");
FileOutputStream fos = new FileOutputStream(file);	//还可以追加,第二个参数写 true
String s = "\nPPPPPPPPPPPPPPPP66车厘子哈哈……&777";
byte b[] = s.getBytes();
fos.write(b);
fos.close();

3、字符流输入输出

输入

//1.创建文件对象
File file = new File("D:\\soft\\ApiProject\\src\\IO20210129\\a.txt");
//2.打开FileReader流
FileReader fr = new FileReader(file);
//3.临时存储
int temp = 0;
//转成String类型可有可无
StringBuffer sb = new StringBuffer("");
while (( temp = fr.read())!=-1){
    sb.append((char)temp);
}
System.out.println(sb);
//4.关闭
fr.close();

输出

File file = new File("D:\\soft\\ApiProject\\src\\IO20210129\\a.txt");
FileWriter fw = new FileWriter(file,true);		//不覆盖的写
String s = "HelloJava";
fw.write(s);
fw.close();

4、缓冲流的输入输出

输入

FileReader fr = new FileReader("D:\\soft\\ApiProject\\src\\IO20210129\\a.txt");
BufferedReader br = new BufferedReader(fr);
String temp;
StringBuffer sb = new StringBuffer();
while (null!=(temp=br.readLine())){     //readLine返回值:String
    sb.append(temp+"\n");
}
System.out.println(sb);
br.close();
fr.close();

输出

FileWriter fw = new FileWriter("D:\\soft\\ApiProject\\src\\IO20210129\\a.txt",true);
BufferedWriter bw = new BufferedWriter(fw);
String s = "\n1@Ya哭";
bw.write(s);
bw.close();
fw.close();

5、二进制流的输入输出

直接拷贝

import java.io.*;

/**
 * @Author shall潇
 * @Date 2021/2/1
 * @Description     二进制文件拷贝
 */
public class TestDataStream {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\soft\\ApiProject\\src\\IO20210201\\Test2\\hh.jpg");
        FileOutputStream fow = new FileOutputStream("D:\\soft\\ApiProject\\src\\IO20210201\\Test2\\hh2.jpg");
        DataInputStream dis = new DataInputStream(fis);
        DataOutputStream dos = new DataOutputStream(fow);
//        //1.第一种方式
//        int temp;
//        while ((temp=dis.read())!=-1){
//            dos.write(temp);
//        }

        //2.第二种方式
        byte[] b = new byte[dis.available()];
        while (dis.read(b)!=-1)
            dos.write(b);

        dos.close();
        dis.close();
        fow.close();
        fis.close();
    }
}

6、对象流的输入输出

在讲对象流之前,要提一下:序列化反序列化
在这里插入图片描述
在这里插入图片描述
Student类

public class Student implements Serializable {
    private int id;
    private String name;
    private String address;

    public Student(int id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }
    ...		//还有getter,setter,toString ,这里就不粘了
}

测试类:

Student s1 = new Student(1001,"Jack","美国");
FileInputStream fis = new FileInputStream("D:\\soft\\ApiProject\\src\\IO20210201\\Test3\\aaa.txt");
FileOutputStream fos = new FileOutputStream("D:\\soft\\ApiProject\\src\\IO20210201\\Test3\\aaa.txt",true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
ObjectInputStream ois = new ObjectInputStream(fis);
//1.序列化
oos.writeObject(s1);
//2.反序列化
Object o = ois.readObject();
if(o instanceof Student) {
    Student os = (Student) o;
    System.out.println(os);
}
ois.close();
oos.close();
fos.close();
fis.close();

【注意:一般适合一个对象的序列化和反序列化,多个对象时就会很麻烦,所以我觉得很鸡肋】

例子:
1、实现文件的复制

File file = new File("D:\\soft\\ApiProject\\src\\IO20210129\\Test2\\aa.txt");		//要复制的文件
FileInputStream fis = new FileInputStream(file);
File file2 = new File("D:\\soft\\ApiProject\\src\\IO20210129\\Test2\\b.txt");		//粘贴在这里
FileOutputStream fos = new FileOutputStream(file2);
byte[] b = new byte[fis.available()];
fis.read(b);
//String s = new String(b);		//这两行可加可不加,就是在控制台上看看复制的内容
//System.out.println(s);
fos.write(b);
fis.close();
fos.close();

2、实现文件的遍历
利用递归实现文件的遍历

public class FileSearch {
    public static void search(String inPath) {
        if(null==inPath)
            return;
        File file = new File(inPath);
        if(file.exists()){									//首先判断文件是否存在
            File[] files = file.listFiles();
            if(files.length==0){
                System.out.println("空文件夹");
                return;
            }else {
                for(File f:files){
                    if(f.isDirectory()) {
                        System.out.println(f.getName());	//输出文件夹名
                        search(f.getAbsolutePath());		//如果是目录,就让它继续遍历
                    }else {
                        System.out.println(f.getName());	//如果是文件,输出文件名
                    }
                }
            }
        }else {
            System.out.println("文件不存在");
        }
    }

    public static void main(String[] args) {
        search("D:\\soft\\DeskTopShare");
    }
}

3.统计A–Z和a~z之间字母个数

File file = new File("D:\\soft\\ApiProject\\src\\IO20210201\\homework20210201\\chaar.txt");
FileReader fr = new FileReader(file);
int temp;
int Num[] = new int[26];	//放大写
int num[] = new int[26];	//放小写
int count = 0;
while ((temp=fr.read())!=-1){
    if(temp>=65&&temp<=91){
        temp-='A';
        Num[temp]++;
    }else if(temp>=97&&temp<=123){
        temp-='a';
        num[temp]++;
    }
}
for (int i = 0; i < Num.length; i++) {
    System.out.println((char) (i+'A')+" : "+Num[i]);
}
for (int i = 0; i < num.length; i++) {
    System.out.println((char) (i+'a')+" : "+num[i]);
}
fr.close();

4.wordcount(统计单词个数…)
input文件
在这里插入图片描述
测试类

BufferedReader br = new BufferedReader(new FileReader("D:\\peixun\\soft\\ApiProject\\src\\exam\\input.txt"));
        String temp;
        HashMap<String,Integer> map = new HashMap<>();
        while (null!=(temp=br.readLine())){
            String name = temp.split(" ")[0];
            String dianji = temp.split(" ")[1];
            int dj = Integer.valueOf(dianji);
            if(!map.containsKey(name)){ 	//不包含直接插入
                map.put(name,dj);
            }else {						    //如果包含取出之前的与读入的相加
                map.put(name,Integer.valueOf(map.get(name))+dj);	
            }
        }
        System.out.println(map);
        br.close();

四、各种流之间的速度对比

网上找的,不全,但是可以肯定的是
缓冲流快,二进制流稳定
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43288259/article/details/113398486