java高级04 常见io

IO

注意:当输入流和输出流的地址是同一个,需要先确保完全读完内容再进行输出,不然会导致覆盖掉尚未读取的内容,最佳做法是将文件读取和写入操作分开,并且最好写入到一个新的文件中,最后再替换原文件。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

输入和输出主要由Read和writer
read()从此输入流中读取下一个字节的数据。值字节作为 int 在 0 到 255 范围内返回。如果因为已到达流的末尾而没有可用字节,则返回值 -1
read(byte[] b)将数据读取到byte数组中,读入缓冲区的字节总数,如果因为已到达流的末尾而没有更多数据,则为 -1。
read(byte[] b, int off, int len)从此输入流中读取最多 len 字节的数据到byte字节数组中。如果 len 不为零,则该方法会阻塞,直到某些输入可用;否则,不读取任何字节并返回 0。
write(int b)
将指定字节写入此文件输出流。
write(byte[] b)将指定字节数组中的 b.length 个字节写入此文件输出流。
write(byte[] b, int off, int len)从偏移量 off 开始的指定字节数组中将 len 字节写入此文件输出流。
available() 返回输入流读取预估的字节数

I/O流

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

//创建字节输入流
        OutputStream fos =new FileOutputStream(dest+"\\"+"copy_"+file.getName());

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

字节输入流FileInputStream

public static void in() {
    InputStream is = null;
    try {
        is = new FileInputStream("D:/test.txt");
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
        int len = 0;
       
        while (true) {
         byte[] buffer = new byte[1024];
            try {
                if (((len = is.read(buffer)) == -1)) {
                    break;
                }
                System.out.println(new String(buffer, 0, len));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
}

FileInputStream fis = new FileInputStream("D:\\test.txt");
循环读取文件,read方法返回读取的字节数,一个一个字节去读取内容,如果返回-1表示文件已经读取完毕
int i = fis.read();
//一次读取一个buf大小的字节
 byte[] buf = new byte[1024];
int i = fis.read(buf);
//只读取有效字节数
byte[] buffer = new byte[1024];
    int length;
    while ((length = in.read(buffer)) > 0) {
        out.write(buffer, 0, length);
        }
//关闭流
 in = new FileInputStream("C:\\Users\\h'j'g\\Desktop\\必背单词.txt");
 这里省略了读取和写入操作
 //放在最后,输入流使用了就关闭
 if (in != null) in.close();
 //available() 是Java中某些输入流类提供的方法,用于返回可以从此输入流中无阻塞读取的估计字节数。

字节输出流FileOutputStream

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

//一次写入一个字节
out.write();
//一次读取buf长度的字节
public static void out(){
    try {
        OutputStream os = new FileOutputStream("D:/test.txt");
        os.write("早上好".getBytes());
        os.flush();
        os.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

//构造函数的第二个参数设置为true,表示将以追加模式打开文件。这意味着新的内容将被添加到文件的末尾,而不会覆盖现有的内容。
public static void out(){
    try {
        OutputStream os = new FileOutputStream("D:/test.txt",true);
        os.write("早上好".getBytes());
        os.flush();
        os.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

字符流InputStreamReader/OutputStreamWriter

字符流接收一个字节流作为参数

//字符输入流
public static void in1(){
        Reader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream("D:/test.txt"),"UTF-8");
            
            int len = 0;
            while (true) {
            char[] buffer = new char[1024];
                if ((len = reader.read(buffer)) == -1) {
                    break;
                }
                System.out.println(new String(buffer, 0, len));
            }
        }catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
}
//字符输出流
public static void out1(){
    Writer writer = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream("D:/test.txt",true),"UTF-8");
        writer.write(",洛阳");

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

    }
}

便捷字符流FileWriter/FileReader

Java提供了FileWriter和FileReader简化字符流的读写,new FileWriter等同于new OutputStreamWriter(new FileOutputStream(file, true))

//便捷字符输出流
public static void out3() {
    FileWriter writer = null;
    try {
        writer = new FileWriter("D:/test.txt",true);
        writer.write(",晚上好");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }finally {
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
//便捷字符输入流
public static void in3() {
    FileReader reader = null;
    try {
        reader = new FileReader("D:/test.txt");
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
    int len = 0;
    
    while (true){
    char[] buffer = new char[1024];
        try {
            if (((len = reader.read(buffer)) == -1)){
                break;
            }
            System.out.println(new String(buffer, 0, len));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        }
    try {
        reader.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

缓冲流BufferedReader/BufferedWriter

1.接收一个字符流作为参数,readLine()一次读取一行,自带缓冲区
2.除了 readLine() 方法外,BufferedReader 还有 read() 方法,它可以读取单个字符,返回其 ASCII 值。当达到文件末尾时,返回 -1。
3.readChars(char[] cbuf) 方法可以读取一系列字符并存储到一个字符数组中。此方法返回实际读取的字符数,当达到文件末尾时,返回 -1。

public static void main(String[] args) throws IOException{
        //创建字节输入流
        InputStream in = new FileInputStream("D:\\test.txt");
        //创建字符输入流
        InputStreamReader isr = new InputStreamReader(in, "UTF-8");
        //创建缓冲区
        BufferedReader br = new BufferedReader(isr);
        //这里参数可以是字符输出流OutputStreamWrite也可以是FileWriter
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\test.txt"));
        while(true){
            //读取一行
            String line = br.readLine();
            if(line == null){
                break;
            }
            bw.write(line);
            System.out.println(line);
        }
        br.close();
        isr.close();
        in.close();
        bw.close();
    }

    //也可以这样用
     public static void main(String[] args) {
        String filePath = "example.txt"; // 文件路径

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

对象流ObjectOutputStream/ObjectInputStream

1.想要将对象传输到某处,需要将对象序列化,实现Serializable.
2.跨设备传输对象需要客户端和服务端环境一样,包括目录结构,文件名,包名都要一样
3.如果出现了序列化uid不一样,需要在对象类加个属性serialVersionUID

private static final long serialVersionUID = 1L;
//客户端
public static void main(String[] args) {
        //建立连接
        try {
            Socket socket = new Socket("192.168.119.148",8080);
            //通过socket获得输出流
            OutputStream oos = socket.getOutputStream();
            //创建对象输出流
            ObjectOutputStream oo = new ObjectOutputStream(oos);
            //创建对象
            Student student = new Student("张三",18,1001);
            oo.writeObject(student);
            oo.flush();
            oo.close();
            oos.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
//服务端
public static void main(String[] args) {
        //建立连接
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            //监听器
            Socket socket = serverSocket.accept();
            //获得通道
            InputStream ins = socket.getInputStream();
            ObjectInputStream out = new ObjectInputStream(ins);
            Student s1 = (Student) out.readObject();
            System.out.println(s1.getName());
            System.out.println(s1.getAge());
            System.out.println(s1.getId());
            out.close();
            ins.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student s1 = new Student("张三", 20, 1001);
        // 序列化,把对象转换成字节数组,输出到文件
        //创建对象输出流,参数是字节输出流,两种构造方法,无参和传入字节输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\student.txt"));
        //反序列化,从文件中读取字节数组,转换成对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\student.txt"));
        //写入对象
        oos.writeObject(s1);
        //读取对象
        Student s = (Student) ois.readObject();
        System.out.println(s.getName());
        System.out.println(s.getAge());
        System.out.println(s.getId());
        ois.close();
        //关闭流
        oos.close();

文件File

File.renameTo和Files.move

renameTo 方法返回一个布尔值,表示操作是否成功。如果返回 true,则表示文件重命名成功;如果返回 false,则表示重命名失败

Files.move可以实现文件的重命名或移动到不同的位置。Files.move 提供了一种安全的方式来移动文件,因为它保证了操作的原子性(要么完成,要么不执行任何更改)。
如果你需要跨文件系统移动文件,或者需要更可靠的重命名操作,建议使用 java.nio.file.Files.move 方法

//renameTo
public static void main(String[] args) {
        File sourceFile = new File("source.txt");
        File targetFile = new File("target.txt");

        if (sourceFile.renameTo(targetFile)) {
            System.out.println("文件重命名成功!");
        } else {
            System.out.println("文件重命名失败!");
        }
    }
//Files.move
 public static void main(String[] args) {
    //这里也能直接定义字符串,后面使用Files.move时当参数传入即可
        Path sourcePath = Paths.get("source.txt");
        Path targetPath = Paths.get("target.txt");

        try {
            Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件已成功移动。");
        } catch (Exception e) {
            System.err.println("移动文件时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
//sourcePath: 要移动的文件或目录的路径。
//targetPath: 移动到的目标位置的路径。
//StandardCopyOption.REPLACE_EXISTING: 如果目标位置已经存在一个文件或目录,这个选项将会覆盖现有的文件或目录。如果没有这个选项,如果目标位置已经有相同名称的文件或目录,Files.move 会抛出 FileAlreadyExistsException。
public static void main(String[] args) {
        //创建文件对象,把要操作的文件转换成Java中的File对象
        File file = new File("C:\\Users\\h'j'g\\Desktop\\必背单词.txt");
        //判断文件是否存在
        Boolean isExists = file.exists();
        System.out.println(isExists);
        //判断文件是否是文件.isFile();
        System.out.println(file.isFile());
        //判断文件是否是目录.isDirectory();
        System.out.println(file.isDirectory());
        //获取文件相对路径.getPath();
        System.out.println(file.getPath());
        //获取绝对路径.getAbsolutePath();
        System.out.println(file.getAbsolutePath());
        //获取文件名.getName();
        System.out.println(file.getName());
        //删除文件.delete();
        System.out.println(file.delete());
        //创建文件.createNewFile();
        try {
            file.createNewFile();
            System.out.println("创建文件成功");
        }catch (IOException e){
            throw new RuntimeException("创建文件失败");
            //e.printStackTrace();
        }
        //获取文件大小.length();
        System.out.println(file.length());

    }
Java高级开发常见笔试题主要包括以下几个方面:多线程、集合框架、IO流、异常处理以及设计模式。 多线程方面,常见的问题有如何创建线程、线程安全、线程间通信等。例如,可以通过继承Thread类或实现Runnable接口来创建线程,可以使用synchronized关键字或Lock接口来实现线程安全,可以使用wait()、notify()、notifyAll()方法来实现线程间的通信。 集合框架方面,常见问题包括ArrayList和LinkedList的区别、HashMap和HashTable的区别、如何使用迭代器等。例如,ArrayList和LinkedList的区别在于前者适用于随机访问,后者适用于插入、删除多的场景;HashMap和HashTable的区别在于前者非线程安全,后者线程安全;迭代器可以使用Iterator接口来遍历集合元素。 IO流方面,常见问题涉及输入输出流的分类、字节流和字符流的区别、File类的使用等。例如,输入输出流可以分为字节流和字符流,字节流适用于二进制文件,字符流适用于文本文件;字节流以字节为单位读写数据,字符流以字符为单位读写数据;File类可以用来操作文件和目录。 异常处理方面,常见问题有如何处理异常、自定义异常等。例如,可以使用try-catch语句来处理异常,可以使用throw关键字来抛出异常,还可以自定义异常类来满足特定需求。 设计模式方面,常见问题包括单例模式、工厂模式、观察者模式等。例如,单例模式可以通过私有构造函数和静态方法来确保类只有一个实例;工厂模式可以通过工厂类来创建对象,避免直接创建对象;观察者模式可以通过定义观察者和被观察者接口,实现对象间的通知和更新。 以上只是一些常见的笔试题,实际上Java高级开发的内容非常广泛,需要掌握的知识也比较多。希望以上回答能够帮助到您。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值