J2EE练习及面试题_chapter13 IO流_上

本文涉及的产品
系统运维管理,不限时长
简介: J2EE练习及面试题_chapter13 IO流_上

题目01

/**
 * 测试FileInputStream和FileOutputStream的使用
 * <p>
 * 结论:
 * 1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
 * 2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,excel...),使用字节流处理
 */
//使用字节流FileInputStream处理文本文件,可能出现乱码。
package com.jerry.java;
import org.junit.Test;
import java.io.*;
/**
 * @author jerry_jy
 * @create 2022-10-08 17:36
 */
public class FileInputOutputStreamTest {
    @Test
    public void testFileInputStream() {
        FileInputStream fis = null;
        try {
            File file = new File("hello.txt");
            fis = new FileInputStream(file);
            byte[] buffer = new byte[5];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                System.out.println(new String(buffer, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    实现对图片的复制操作
     */
    @Test
    public void testFileInputOutputStream() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File srcFile = new File("java.jpg");
            File destFile = new File("java1.jpg");
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            byte[] buffer = new byte[5];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //指定路径下文件的复制
    public void copyFile(String srcPath, String destPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void testCopyFile(){
        long start = System.currentTimeMillis();
        String srcPath = "E:\\0课程资料\\密码学\\1.mp4";
        String destPath = "E:\\0课程资料\\密码学\\1_1.mp4";
        copyFile(srcPath, destPath);
        long end = System.currentTimeMillis();
        System.out.println("复制操作花费的时间为:" + (end - start));//2619
    }
}

题目02

/*
将hello.txt文件内容读入程序中,并输出到控制台
说明点:
1. read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
2. 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
3. 读入的文件一定要存在,否则就会报FileNotFoundException。
    @Test
    public void testFileReader() {
        FileReader fileReader = null;
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");
            //2.提供具体的流
            fileReader = new FileReader(file);
            //3.数据的读入
            //read():返回读入的一个字符。如果达到文件末尾,返回-1
            int data;
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);//这里记得一定要强转为char类型,不然读出来就是ASCII
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //4.流的关闭操作
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //对read()操作升级:使用read的重载方法
    @Test
    public void testFileReader1() {
        FileReader fileReader = null;
        try {
            //1.File类的实例化
            File file = new File("hello.txt");
            //2.FileReader流的实例化
            fileReader = new FileReader(file);
            //3.读入的操作
            //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
            char[] cbuf = new char[5];
            int len;
            while ((len = fileReader.read(cbuf)) != -1) {
//                System.out.print(cbuf);
                //方式一:
                //错误的写法
//                for(int i = 0;i < cbuf.length;i++){
//                    System.out.print(cbuf[i]);
//                }
                //正确的写法
//                for(int i = 0;i < len;i++){
//                    System.out.print(cbuf[i]);
//                }
                //方式二:
                //错误的写法,对应着方式一的错误的写法
//                String str = new String(cbuf);
//                System.out.print(str);
                //正确的写法
                String str = new String(cbuf, 0, len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

题目03

/*
从内存中写出数据到硬盘的文件里。
说明:
1. 输出操作,对应的File可以不存在的。并不会报异常
2.
 File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
 File对应的硬盘中的文件如果存在:
        如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
        如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
 */
    @Test
    public void testFileWriter() {
        FileWriter fileWriter = null;
        try {
            //1.提供File类的对象,指明写出到的文件
            File file = new File("hello1.txt");
            fileWriter = new FileWriter(file, false);
            //3.写出的操作
            fileWriter.write("I hava a dream!");
            fileWriter.write("人需要有一个梦想!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //4.流资源的关闭
                if (fileWriter != null) {
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void testFileReaderFileWriter() {
        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            //1.创建File类的对象,指明读入和写出的文件
            File srcFile = new File("hello.txt");
            File destFile = new File("hello2.txt");
            //2.创建输入流和输出流的对象
            fileReader = new FileReader(srcFile);
            fileWriter = new FileWriter(destFile);
            //3.数据的读入和写出操作
            char[] cbuf = new char[5];
            int len;
            while ((len = fileReader.read(cbuf)) != -1) {
                fileWriter.write(cbuf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fileWriter != null) {
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

题目04

File类的使用
package com.jerry.java;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
/**
 * @author jerry_jy
 * @create 2022-10-07 20:29
 */
public class FileTest {
    public static void main(String[] args) throws IOException {
        File file = new File("D:" + File.separator + "2.txt");
        System.out.println("**********创建文件*********");
        System.out.println(file.createNewFile());//false
        System.out.println("**********获取绝对路径*********");
        System.out.println(file.getAbsolutePath());//D:\2.txt
        System.out.println("**********获取名称*********");
        System.out.println(file.getName());//2.txt
        System.out.println("**********获取文件长度(即:字节数)。不能获取目录的长度*********");
        System.out.println(file.length());//0
        System.out.println("**********获取最后一次的修改时间,毫秒值*********");
        System.out.println(file.lastModified());//1665148556505
        System.out.println("**********判断是否是文件目录*********");
        System.out.println(file.isDirectory());//false
        System.out.println("**********判断是否是文件*********");
        System.out.println(file.isFile());//true
        System.out.println("**********判断是否存在*********");
        System.out.println(file.exists());//true
        System.out.println("**********判断是否可读*********");
        System.out.println(file.canRead());//true
        System.out.println("**********判断是否可写*********");
        System.out.println(file.canWrite());//true
        System.out.println("**********判断是否隐藏*********");
        System.out.println(file.isHidden());//false
        System.out.println("**********创建文件。若文件存在,则不创建,返回false*********");
        System.out.println(new File("D:" + File.separator + "3.txt").createNewFile());//false
        System.out.println("**********删除文件或者文件夹*********");
        System.out.println(file.delete());//true
        File dir1 = new File("D:/IOTest/dir1");
        if (!dir1.exists()) { // 如果D:/IOTest/dir1不存在,就创建为目录
            dir1.mkdir();
        }
        // 创建以dir1为父目录,名为"dir2"的File对象
        File dir2 = new File(dir1, "dir2");
        if (!dir2.exists()) { // 如果还不存在,就创建为目录
            dir2.mkdirs();
        }
        File dir4 = new File(dir1, "dir3/dir4");
        if (!dir4.exists()) {
            dir4.mkdirs();
        }
        // 创建以dir2为父目录,名为"test.txt"的File对象
        File file1 = new File(dir2, "test.txt");
        if (!file1.exists()) { // 如果还不存在,就创建为文件
            file1.createNewFile();
        }
    }
    /*
    public boolean renameTo(File dest):把文件重命名为指定的文件路径
     比如:file1.renameTo(file2)为例:
        要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
     */
    @Test
    public void test1(){
        File file1 = new File("hello.txt");
        File file2 = new File("D:\\io\\hi.txt");
        boolean renameTo = file2.renameTo(file1);
        System.out.println(renameTo);
    }
}

题目05

/**
 * 处理流之一:缓冲流的使用
 * <p>
 * 1.缓冲流:
 * BufferedInputStream
 * BufferedOutputStream
 * BufferedReader
 * BufferedWriter
 * <p>
 * 2.作用:提供流的读取、写入的速度
 * 提高读写速度的原因:内部提供了一个缓冲区
 * <p>
 * 3. 处理流,就是“套接”在已有的流的基础上。
 */
package com.jerry.java;
import org.junit.Test;
import java.io.*;
/**
 * @author jerry_jy
 * @create 2022-10-08 18:12
 */
public class BufferedTest {
    /*
    实现非文本文件的复制
     */
    @Test
    public void BufferedStreamTest() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.造文件
            File srcFile = new File("java.jpg");
            File destFile = new File("java2.jpg");
            //2.造流
            //2.1 造节点流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2 造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.复制的细节:读取、写入
            byte[] buffer = new byte[10];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
                bos.flush();//刷新缓冲区
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //要求:先关闭外层的流,再关闭内层的流
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
//        fos.close();
//        fis.close();
    }
    //实现文件复制的方法
    public void copyFileWithBuffered(String srcPath, String destPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.造文件
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.造流
            //2.1 造节点流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2 造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.复制的细节:读取、写入
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //要求:先关闭外层的流,再关闭内层的流
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
//        fos.close();
//        fis.close();
    }
    @Test
    public void testCopyFileWithBuffered() {
        long start = System.currentTimeMillis();
        String srcPath = "E:\\0课程资料\\密码学\\1.mp4";
        String destPath = "E:\\0课程资料\\密码学\\1_1.mp4";
        copyFileWithBuffered(srcPath, destPath);
        long end = System.currentTimeMillis();
        System.out.println("复制操作花费的时间为:" + (end - start));//336
    }
    /*
    使用BufferedReader和BufferedWriter实现文本文件的复制
     */
    @Test
    public void testBufferedReaderBufferedWriter() {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(new File("dbcp.txt")));
            bw = new BufferedWriter(new FileWriter(new File("dbcp_1.txt")));
            //读写操作
            //方式一:使用char[]数组
//            char[] cbuf = new char[10];
//            int len;
//            while ((len=br.read(cbuf))!=-1){
//                bw.write(cbuf, 0, len);
//                bw.flush();
//            }
            //方式二:使用String
            String data;
            while ((data = br.readLine()) != null) {
                //方法一:
//                bw.write(data + "\n");//data中不包含换行符
                //方法二:
                bw.write(data);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (bw!=null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (br!=null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

题目06

/**
 * 处理流之二:转换流的使用
 * 1.转换流:属于字符流
 * InputStreamReader:将一个字节的输入流转换为字符的输入流
 * OutputStreamWriter:将一个字符的输出流转换为字节的输出流
 * <p>
 * 2.作用:提供字节流与字符流之间的转换
 * <p>
 * 3. 解码:字节、字节数组  --->字符数组、字符串
 * 编码:字符数组、字符串 ---> 字节、字节数组
 * <p>
 * <p>
 * 4.字符集
 * ASCII:美国标准信息交换码。
 * 用一个字节的7位可以表示。
 * ISO8859-1:拉丁码表。欧洲码表
 * 用一个字节的8位表示。
 * GB2312:中国的中文编码表。最多两个字节编码所有字符
 * GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
 * Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
 * UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
 */
package com.jerry.java;
import org.junit.Test;
import java.io.*;
/**
 * @author jerry_jy
 * @create 2022-10-08 19:25
 */
public class InputStreamReaderTest {
    //InputStreamReader的使用,实现字节的输入流到字符的输入流的转换
    @Test
    public void test1() {
        InputStreamReader isr = null;
        try {
            FileInputStream fis = new FileInputStream("dbcp.txt");
            isr = new InputStreamReader(fis, "UTF-8");
            char[] cbuf = new char[20];
            int len;
            while ((len = isr.read(cbuf)) != -1) {
                System.out.println(new String(cbuf, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    此时处理异常的话,仍然应该使用try-catch-finally
    综合使用InputStreamReader和OutputStreamWriter
 */
    @Test
    public void test2() throws Exception {
        //1.造文件、造流
        File file1 = new File("dbcp.txt");
        File file2 = new File("dbcp_gbk");
        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
        //2.读写过程
        char[] cbuf = new char[20];
        int len;
        while ((len= isr.read(cbuf))!=-1){
            osw.write(cbuf, 0, len);
        }
        //3.关闭资源
        osw.close();
        isr.close();
    }
}

题目07

/**
 * 对象流的使用
 * 1.ObjectInputStream 和 ObjectOutputStream
 * 2.作用:用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
 * <p>
 * 3.要想一个java对象是可序列化的,需要满足相应的要求。见Person.java
 * <p>
 * 4.序列化机制:
 * 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种
 * 二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。
 * 当其它程序获取了这种二进制流,就可以恢复成原来的Java对象。
 */
package com.jerry.java;
import org.junit.Test;
import java.io.*;
/**
 * @author jerry_jy
 * @create 2022-10-09 11:19
 */
public class ObjectInputOutputStreamTest {
    /*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream实现
 */
    @Test
    public void testObjectOutputStream() {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(new File("object.dat")));
            oos.writeObject(new String("好好学习"));
            oos.flush();
            oos.writeObject(new Person("Jerry", 22));
            oos.flush();
            oos.writeObject(new Person("Tom", 23, 1001, new Account(8000.0)));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    反序列化:将磁盘文件中的对象还原为内存中的一个java对象
    使用ObjectInputStream来实现
    */
    @Test
    public void testObjectInputStream() {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));
            Object obj = ois.readObject();
            String str = (String) obj;
            Person p1 = (Person) ois.readObject();
            Person p2 = (Person) ois.readObject();
            System.out.println(str);
            System.out.println(p1);
            System.out.println(p2);
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

题目08

/*
1.标准的输入、输出流
1.1
System.in:标准的输入流,默认从键盘输入
System.out:标准的输出流,默认从控制台输出
1.2
System类的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定输入和输出的流。
1.3练习:
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,
直至当输入“e”或者“exit”时,退出程序。
方法一:使用Scanner实现,调用next()返回一个字符串
方法二:使用System.in实现。System.in  --->  转换流 ---> BufferedReader的readLine()
 */
    public static void main(String[] args) {
        // 方式一:采用scanner.next()方法
        while (true){
            System.out.println("从键盘输入字符串:");
            Scanner scanner = new Scanner(System.in);
            String str = scanner.next();
            if ("e".equalsIgnoreCase(str)||"exit".equalsIgnoreCase(str)){
                System.out.println("程序结束!");
                break;
            }
            System.out.println(str.toUpperCase());
        }
        // 方式二:采用BufferedReader
        BufferedReader br = null;
        while (true) {
            try {
                InputStreamReader isr = new InputStreamReader(System.in);
                br = new BufferedReader(isr);
                System.out.println("从键盘输入字符串:");
                String str = br.readLine();
                if ("e".equalsIgnoreCase(str) || "exit".equalsIgnoreCase(str)) {
                    System.out.println("程序结束!");
                    break;
                }
                System.out.println(str.toUpperCase());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

题目09

 /*
2. 打印流:PrintStream 和PrintWriter
2.1 提供了一系列重载的print() 和 println()
2.2 练习:
 */
    @Test
    public void test2() {
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("D:\\io\\1.txt"));
            ps = new PrintStream(fos, true);
            if (ps != null) {
                System.out.println(ps);
            }
            for (int i = 0; i <= 255; i++) {
                System.out.println((char) i);
                if (i % 50 == 0) {
                    System.out.println();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
        }
    }

题目10

/*
3. 数据流
3.1 DataInputStream 和 DataOutputStream
3.2 作用:用于读取或写出基本数据类型的变量或字符串
练习:将内存中的字符串、基本数据类型的变量写出到文件中。
注意:处理异常的话,仍然应该使用try-catch-finally.
 */
    @Test
    public void test3() {
        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(new FileOutputStream(new File("data.txt")));
            dos.writeUTF("金阳");
            dos.flush();
            dos.writeInt(123);
            dos.flush();
            dos.writeBoolean(true);
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

题目11

/*
将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
 */
    @Test
    public void test4() {
        DataInputStream dis=null;
        try {
             dis = new DataInputStream(new FileInputStream("data.txt"));
            String name = dis.readUTF();
            int age = dis.readInt();
            boolean isMale = dis.readBoolean();
            System.out.println("name: " + name);
            System.out.println("age: " + age);
            System.out.println("Male: " + isMale);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (dis!=null){
                    dis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

题目12

/**
 * 1. jdk 7.0 时,引入了 Path、Paths、Files三个类。
 * 2.此三个类声明在:java.nio.file包下。
 * 3.Path可以看做是java.io.File类的升级版本。也可以表示文件或文件目录,与平台无关
 * <p>
 * 4.如何实例化Path:使用Paths.
 * static Path get(String first, String … more) : 用于将多个字符串串连成路径
 * static Path get(URI uri): 返回指定uri对应的Path路径
 */
package com.jerry.java;
    /**
     * 1. jdk 7.0 时,引入了 Path、Paths、Files三个类。
     * 2.此三个类声明在:java.nio.file包下。
     * 3.Path可以看做是java.io.File类的升级版本。也可以表示文件或文件目录,与平台无关
     * <p>
     * 4.如何实例化Path:使用Paths.
     * static Path get(String first, String … more) : 用于将多个字符串串连成路径
     * static Path get(URI uri): 返回指定uri对应的Path路径
     */
import org.junit.Test;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
 * @author jerry_jy
 * @create 2022-10-11 11:17
 */
public class PathTest {
    //如何使用Paths实例化Path
    @Test
    public void test1() {
        Path path1 = Paths.get("D:\\nio\\hello.txt");//new File(String filepath)
        Path path2 = Paths.get("d:\\", "nio\\hello.txt");//new File(String parent,String filename);
        System.out.println(path1);//d:\nio\hello.txt
        System.out.println(path2);//d:\nio\hello.txt
        Path path3 = Paths.get("d:\\", "nio");
        System.out.println(path3);//d:\nio
    }
    //Path中的常用方法
    @Test
    public void test2() {
        Path path1 = Paths.get("d:\\", "nio\\nio1\\nio2\\hello.txt");
        Path path2 = Paths.get("hello.txt");
//    String toString() : 返回调用 Path 对象的字符串表示形式
        System.out.println(path1);//d:\nio\nio1\nio2\hello.txt
//    boolean startsWith(String path) : 判断是否以 path 路径开始
        System.out.println(path1.startsWith("d:\\nio"));//true
//    boolean endsWith(String path) : 判断是否以 path 路径结束
        System.out.println(path1.endsWith("hello.txt"));//true
//    boolean isAbsolute() : 判断是否是绝对路径
        System.out.println(path1.isAbsolute() + "~");//true~
        System.out.println(path2.isAbsolute() + "~");//false~
//    Path getParent() :返回Path对象包含整个路径,不包含 Path 对象指定的文件路径
        System.out.println(path1.getParent());//d:\nio\nio1\nio2
        System.out.println(path2.getParent());//null
//    Path getRoot() :返回调用 Path 对象的根路径
        System.out.println(path1.getRoot());//d:\
        System.out.println(path2.getRoot());//null
//    Path getFileName() : 返回与调用 Path 对象关联的文件名
        System.out.println(path1.getFileName() + "~");//hello.txt~
        System.out.println(path2.getFileName() + "~");//hello.txt~
//    int getNameCount() : 返回Path 根目录后面元素的数量
//    Path getName(int idx) : 返回指定索引位置 idx 的路径名称
        for (int i = 0; i < path1.getNameCount(); i++) {
            System.out.println(path1.getName(i) + "*****");
        }
//    Path toAbsolutePath() : 作为绝对路径返回调用 Path 对象
        System.out.println(path1.toAbsolutePath());//d:\nio\nio1\nio2\hello.txt
        System.out.println(path2.toAbsolutePath());//E:\CodeLife\IdeaProject\JVM\chapter13\hello.txt
//    Path resolve(Path p) :合并两个路径,返回合并后的路径对应的Path对象
        Path path3 = Paths.get("d:\\", "nio");
        Path path4 = Paths.get("nioo\\hi.txt");
        path3 = path3.resolve(path4);
        System.out.println(path3);//d:\nio\nioo\hi.txt
//    File toFile(): 将Path转化为File类的对象
        File file = path1.toFile();//Path--->File的转换
//
        Path newPath = file.toPath();//File--->Path的转换
    }
}

题目13

/**
 * RandomAccessFile的使用
 * 1.RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
 * 2.RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
 * <p>
 * 3.如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
 * 如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)
 * <p>
 * 4. 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果
 */
package com.jerry.java;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
 * @author jerry_jy
 * @create 2022-10-10 15:25
 */
public class RandomAccessFileTest {
    @Test
    public void test1() {
        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            raf1 = new RandomAccessFile(new File("java.jpg"), "r");
            raf2 = new RandomAccessFile(new File("java2.jpg"), "rw");
            byte[] buffer = new byte[1024];
            int len;
            while ((len = raf1.read(buffer)) != -1) {
                raf2.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (raf1 != null) {
                    raf1.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (raf2 != null) {
                    raf2.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test2(){
        RandomAccessFile raf =null;
        try {
             raf = new RandomAccessFile("hello.txt","rw");
             raf.seek(3);;
            raf.write("xyz".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (raf!=null){
                    raf.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    使用RandomAccessFile实现数据的插入效果
     */
    @Test
    public void test3() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("hello.txt", "rw");
        raf.seek(3);
        StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
        byte[] buffer = new byte[20];
        int len;
        while ((len=raf.read(buffer))!=-1){
            builder.append(new String(buffer,0,len));
        }
        raf.seek(3);
        raf.write("xyz".getBytes());
        raf.write(builder.toString().getBytes());
        raf.close();
    }
}


相关文章
|
4月前
|
存储 网络协议 Java
程序员的23大IO&NIO面试问题及答案
程序员的23大IO&NIO面试问题及答案
|
4月前
|
安全 网络安全 数据安全/隐私保护
CocosCreator 面试题(十四)Cocos Creator WebSocket 、Socket.IO分别是什么?
CocosCreator 面试题(十四)Cocos Creator WebSocket 、Socket.IO分别是什么?
272 0
|
6天前
|
安全 Java API
【Java面试题汇总】Java基础篇——String+集合+泛型+IO+异常+反射(2023版)
String常量池、String、StringBuffer、Stringbuilder有什么区别、List与Set的区别、ArrayList和LinkedList的区别、HashMap底层原理、ConcurrentHashMap、HashMap和Hashtable的区别、泛型擦除、ABA问题、IO多路复用、BIO、NIO、O、异常处理机制、反射
【Java面试题汇总】Java基础篇——String+集合+泛型+IO+异常+反射(2023版)
|
3月前
|
存储 缓存 Java
Java基础17-读懂Java IO流和常见面试题(二)
Java基础17-读懂Java IO流和常见面试题(二)
38 0
|
3月前
|
存储 Java Unix
Java基础17-读懂Java IO流和常见面试题(一)
Java基础16-读懂Java IO流和常见面试题(一)
54 0
|
4月前
|
存储 Java 数据库
[Java 基础面试题] IO相关
[Java 基础面试题] IO相关
|
11月前
|
Java
【面试题精讲】Java IO 模型
【面试题精讲】Java IO 模型
|
10月前
|
存储 网络协议 安全
探索Java通信面试的奥秘:揭秘IO模型、选择器和网络协议,了解面试中的必备知识点!
通过深入探索Java通信面试的奥秘,我们将揭秘Java中的三种I/O模型(BIO、NIO和AIO)、选择器(select、poll和epoll)以及网络协议(如HTTP和HTTPS),帮助您了解在面试中必备的知识点。这些知识点对于网络编程和系统安全方面的求职者来说至关重要,掌握它们将为您的职业发展打下坚实的基础!
|
30天前
|
存储 Java
【IO面试题 四】、介绍一下Java的序列化与反序列化
Java的序列化与反序列化允许对象通过实现Serializable接口转换成字节序列并存储或传输,之后可以通过ObjectInputStream和ObjectOutputStream的方法将这些字节序列恢复成对象。
|
2月前
|
Java 大数据
解析Java中的NIO与传统IO的区别与应用
解析Java中的NIO与传统IO的区别与应用