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

简介: J2EE练习及面试题_chapter13 IO流_中

题目14

Contain the methods for reading int, double, float, boolean, short, byte and string values from the keyboard
package com.jerry.java;
// MyInput.java: Contain the methods for reading int, double, float, boolean, short, byte and string values from the keyboard
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 * @author jerry_jy
 * @create 2022-10-11 11:36
 */
public class MyInput {
    // Read a string from the keyboard
    public static String readString() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // Declare and initialize the string
        String string = "";
        // Get the string from the keyboard
        try {
            string = br.readLine();
        } catch (IOException ex) {
            System.out.println(ex);
        }
        // Return the string obtained from the keyboard
        return string;
    }
    // Read an int value from the keyboard
    public static int readInt() {
        return Integer.parseInt(readString());
    }
    // Read a double value from the keyboard
    public static double readDouble() {
        return Double.parseDouble(readString());
    }
    // Read a byte value from the keyboard
    public static double readByte() {
        return Byte.parseByte(readString());
    }
    // Read a short value from the keyboard
    public static double readShort() {
        return Short.parseShort(readString());
    }
    // Read a long value from the keyboard
    public static double readLong() {
        return Long.parseLong(readString());
    }
    // Read a float value from the keyboard
    public static double readFloat() {
        return Float.parseFloat(readString());
    }
    public static void main(String[] args) {
//        System.out.println(MyInput.readString());
        System.out.println(MyInput.readInt());
    }
}

题目15

/*
利用File构造器,new 一个文件目录file
1)在其中创建多个文件和目录
2)编写方法,实现删除file中指定文件的操作
 */
package com.jerry.exer;
import java.io.File;
import java.io.IOException;
/**
 * @author jerry_jy
 * @create 2022-10-07 21:33
 */
public class Exer1 {
    public static void main(String[] args) throws IOException {
        File dir1 = new File("D:/io/dir1");
        if (!dir1.exists()){
            dir1.mkdir();
        }
        File dir2 = new File(dir1, "dir2");
        if (!dir2.exists()){
            dir2.mkdir();
        }
        File dir3 = new File(dir1, "dir3/dir4/dir5");
        if (!dir3.exists()){
            dir3.mkdirs();
        }
        File file = new File(dir2, "2.txt");
        if (!file.exists()){
            file.createNewFile();
        }
        File file1 = new File(dir3, "3.txt");
        if (!file1.exists()){
            file1.createNewFile();
        }
    }
}

题目16

/*
 判断指定目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称
 */
package com.jerry.exer;
import org.junit.Test;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
/**
 * @author jerry_jy
 * @create 2022-10-07 21:45
 */
public class Exer2 {
    public static void main(String[] args) {
        File srcFile = new File("D:\\code");
        String[] fileNames = srcFile.list();
        for (String fileName : fileNames) {
            if (fileName.endsWith(".jpg")){
                System.out.println(fileName);
            }
        }
    }
    @Test
    public void test2(){
        File srcFile = new File("d:\\code");
        File[] listFiles = srcFile.listFiles();
        for(File file : listFiles){
            if(file.getName().endsWith(".jpg")){
                System.out.println(file.getAbsolutePath());//d:\code\1.jpg
            }
        }
    }
    /*
     * File类提供了两个文件过滤器方法
     * public String[] list(FilenameFilter filter)
     * public File[] listFiles(FileFilter filter)
     */
    @Test
    public void test3(){
        File srcFile = new File("D:\\code");
        for (File file : srcFile.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".jpg");
            }
        })) {
            System.out.println(file.getAbsolutePath());//D:\code\1.jpg
        }
    }
}

题目17

/*
遍历指定目录所有文件名称,包括子文件目录中的文件。
拓展1:并计算指定目录占用空间的大小
拓展2:删除指定文件目录及其下的所有文件
 */
package com.jerry.exer;
import java.io.File;
/**
 * @author jerry_jy
 * @create 2022-10-08 9:33
 */
public class Exer3 {
    public static void main(String[] args) {
        // 递归:文件目录
        /* 打印出指定目录所有文件名称,包括子文件目录中的文件 */
        // 1.创建目录对象
        File dir = new File("D:\\io");
        // 2.打印目录的子文件
        printSubFile(dir);
        System.out.println(getDirSize(dir));
        deleteDir(dir);
    }
    public static void printSubFile(File dir) {
        // 打印目录的子文件
        for (File subFile : dir.listFiles()) {
            if (subFile.isDirectory()) {
                printSubFile(subFile);
            } else {
                System.out.println(subFile.getAbsolutePath());
            }
        }
    }
    public static long getDirSize(File file) {
        // file是文件,那么直接返回file.length()
        // file是目录,把它的下一级的所有大小加起来就是它的总大小
        long size = 0;
        if (file.isFile()) {
            size += file.length();
        } else {
            for (File listFile : file.listFiles()) {
                size += getDirSize(listFile);
            }
        }
        return size;
    }
    public static void deleteDir(File file) {
        // 如果file是文件,直接delete
        // 如果file是目录,先把它的下一级干掉,然后删除自己
        if (file.isDirectory()) {
            for (File listFile : file.listFiles()) {
                deleteDir(listFile);
            }
        }
        file.delete();
    }
}

题目18

/*
分别使用节点流:FileInputStream、FileOutputStream和缓冲流:
BufferedInputStream、BufferedOutputStream实现文本文件/图片/视频文件的
复制。并比较二者在数据复制方面的效率
 */
package com.jerry.exer;
import org.junit.Test;
import java.io.*;
/**
 * @author jerry_jy
 * @create 2022-10-11 10:15
 */
public class Exer5 {
    @Test
    public void test1() throws IOException {
        //FileInputStream-FileOutputStream实现文本文件的复制
        long start = System.currentTimeMillis();
        FileInputStream fis = new FileInputStream("dbcp.txt");
        FileOutputStream fos = new FileOutputStream("dbcp_fis.txt");
        byte[] buffer = new byte[10];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        fis.close();
        long end = System.currentTimeMillis();
        System.out.println("FileInputStream-FileOutputStream实现文本文件的复制,花费:" + (end - start) + "毫秒");//17
    }
    @Test
    public void test2() throws IOException {
        //FileInputStream-FileOutputStream实现图片的复制
        long start = System.currentTimeMillis();
        FileInputStream fis = new FileInputStream("java.jpg");
        FileOutputStream fos = new FileOutputStream("java_fis.jpg");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        fis.close();
        long end = System.currentTimeMillis();
        System.out.println("FileInputStream-FileOutputStream实现图片的复制,花费:" + (end - start) + "毫秒");//1
    }
    @Test
    public void test3() throws IOException {
        //FileInputStream-FileOutputStream实现视频文件的复制
        long start = System.currentTimeMillis();
        FileInputStream fis = new FileInputStream("E:\\0课程资料\\密码学\\1.mp4");
        FileOutputStream fos = new FileOutputStream("E:\\0课程资料\\密码学\\1_fis.mp4");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        fis.close();
        long end = System.currentTimeMillis();
        System.out.println("FileInputStream-FileOutputStream实现视频文件的复制,花费:" + (end - start) + "毫秒");//2320
    }
    @Test
    public void test4() throws IOException {
        //BufferedInputStream-BufferedOutputStream实现文本文件的复制
        long start = System.currentTimeMillis();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("dbcp.txt"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("dbcp_bis.txt"));
        byte[] cbuf = new byte[10];
        int len;
        while ((len=bis.read(cbuf))!=-1){
            bos.write(cbuf, 0, len);
            bos.flush();
        }
        bos.close();
        bis.close();
        long end = System.currentTimeMillis();
        System.out.println("BufferedInputStream-BufferedOutputStream实现文本文件的复制,花费:" + (end - start) + "毫秒");//3
    }
    @Test
    public void test5() throws IOException {
        //BufferedInputStream-BufferedOutputStream实现图片的复制
        long start = System.currentTimeMillis();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("java.jpg"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("java_bis.jpg"));
        byte[] cbuf = new byte[1024];
        int len;
        while ((len=bis.read(cbuf))!=-1){
            bos.write(cbuf, 0, len);
            bos.flush();
        }
        bos.close();
        bis.close();
        long end = System.currentTimeMillis();
        System.out.println("BufferedInputStream-BufferedOutputStream实现图片的复制:" + (end - start) + "毫秒");//1
    }
    @Test
    public void test6() throws IOException {
        //BufferedInputStream-BufferedOutputStream实现视频文件的复制
        long start = System.currentTimeMillis();
        FileInputStream fis = new FileInputStream("E:\\0课程资料\\密码学\\1.mp4");
        FileOutputStream fos = new FileOutputStream("E:\\0课程资料\\密码学\\1_bis.mp4");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        fis.close();
        long end = System.currentTimeMillis();
        System.out.println("FileInputStream-FileOutputStream实现视频文件的复制,花费:" + (end - start) + "毫秒");//1444
    }
}

题目19

/*
实现图片加密操作。
 */
package com.jerry.exer;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @author jerry_jy
 * @create 2022-10-11 10:39
 */
public class Exer6 {
    /*
    实现图片加密操作。
     */
    @Test
    public void test() throws IOException{
        FileInputStream fis = new FileInputStream(new File("java.jpg"));
        FileOutputStream fos = new FileOutputStream(new File("java_secret1.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len=fis.read(buffer))!=-1){
            fos.write(buffer, 0, len^5);
        }
        fos.close();
        fis.close();
    }
}

题目20

/*
获取文本上每个字符出现的次数
提示:遍历文本的每一个字符;字符及出现的次数保存在Map中;将Map中数据写入文件
 */
    /*
说明:如果使用单元测试,文件相对路径为当前module
如果使用main()测试,文件相对路径为当前工程
 */
package com.jerry.exer;
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
 * @author jerry_jy
 * @create 2022-10-11 10:47
 */
public class Exer7 {
    @Test
    public void testWordCount() {
        FileReader fr = null;
        BufferedWriter bw = null;
        try {
            HashMap<Character, Integer> map = new HashMap<>();
            fr = new FileReader("dbcp.txt");
            int data;
            while ((data = fr.read()) != -1) {
                char c = (char) data;
                if (map.get(c) == null) {
                    map.put(c, 1);
                } else {
                    map.put(c, map.get(c) + 1);
                }
            }
            bw = new BufferedWriter(new FileWriter("WordCount.txt"));
            Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
            for (Map.Entry<Character, Integer> entry : entrySet) {
                switch (entry.getKey()) {
                    case ' ':
                        bw.write("空格=" + entry.getValue());
                        break;
                    case '\t':
                        bw.write("tab键=" + entry.getValue());
                        break;
                    case '\r':
                        bw.write("回车=" + entry.getValue());
                        break;
                    case '\n':
                        bw.write("换行=" + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "=" + entry.getValue());
                        break;
                }
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

题目21

/*
在指定的路径下新建一个 .txt 文件 "test.txt",利用程序在文件中写入如下内容:
 */
    @Test
    public void test1() {
        FileWriter fw = null;
        try {
            fw = new FileWriter(new File("test.txt"));
            fw.write("Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于 1995年5月推出的Java程序设计语言和Java平台(即JavaSE, JavaEE, JavaME)的总称。Java 技术具有 卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台、科 学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。在全球云计算和移动互 联网的产业环境下,Java更具备了显著优势和广阔前景。");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

题目22

/*
利用程序读取 test.txt 文件的内容, 并在控制台打印
 */
    @Test
    public void test2() {
        FileReader fr = null;
        try {
            fr = new FileReader("test.txt");
            int data;
            while ((data = fr.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

题目23

/*
利用程序复制 test.txt 为 test1.txt
 */
    @Test
    public void test3() throws IOException {
        Path path1 = Paths.get("test.txt");
        Path path2 = Paths.get("test1.txt");
        Files.copy(path1, path2, StandardCopyOption.REPLACE_EXISTING);
    }

面试01

什么是java序列化,如何实现java序列化?

答:序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。

可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。

序列化是为了解决在对对象流进行读写操作时所引发的问题。

序列化的实现:将需要被序列化的类实现Serializable接口,该接口没有需要实现的方法,

implements Serializable只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。

面试02

使用处理流的优势有哪些?如何识别所使用的流是处理流还是节点流?

【答案】

【优势】对开发人员来说,使用处理流进行输入/输出操作更简单;使用处理流的执行效率更高。

【判别】

处理流的构造器的参数不是一个物理节点,而是已经存在的流。而节点流都是直接以物理IO及节点作为构造器参数的。


面试03

下列程序将从file1.dat文件中读取全部数据,然后写到file2.dat文件中。


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileStreamInOut {
  public static void main(String[] args) {
    try {
      File inFile = new File("_________");
      File outFile = new File("_________");
      FileInputStream fis = new FileInputStream(_________);
      FileOutputStream fos = new FileOutputStream(_________);
      int c;
      while ((c = fis.read()) != -1) {
        fos.write(c);
      }
      _____.close();
      _____.close();
    } catch (FileNotFoundException e) {
      System.out.println("FileStreamsTest:" + e);
    } catch (IOException e) {
      System.out.println("FileStreamTest" + e);
    }
  }
}

面试04

Java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请指出它们分别是哪些类?

【答案】Java中按所操作的数据单元的不同,分为字节流和字符流。

字节流继承于InputStream和OutputStream类;

字符流继承于Reader和Writer。

按流的流向的不同,分为输入流和输出流。

按流的角色来分,可分为节点流和处理流。缓冲流、转换流、对象流和打印流等都属于处理流,使得输入/输出更简单,执行效率更高。


面试05

什么是标准的I/O流?

在java语言中,用stdin表示键盘,用stdout表示监视器。他们均被封装在System类的类变量in 和out中,对应于系统调用System.in和System.out。这样的两个流加上System.err统称为标准流,它们是在System类中声明的3个类变量:

public static InputStream in

publicstaticPrintStream out

public static PrintStream err

面试06

数组有没有length()方法?String有没有length()方法?File有没有length()方法?ArrayList有没有length()方法?

数组没有length()方法,但是有length属性。

String和File有length()方法。

ArrayList没有length()方法,有size()方法获取有效元素个数。


–end–

相关文章
|
4月前
|
存储 网络协议 Java
程序员的23大IO&NIO面试问题及答案
程序员的23大IO&NIO面试问题及答案
|
4月前
|
安全 网络安全 数据安全/隐私保护
CocosCreator 面试题(十四)Cocos Creator WebSocket 、Socket.IO分别是什么?
CocosCreator 面试题(十四)Cocos Creator WebSocket 、Socket.IO分别是什么?
256 0
|
3月前
|
存储 缓存 Java
Java基础17-读懂Java IO流和常见面试题(二)
Java基础17-读懂Java IO流和常见面试题(二)
34 0
|
3月前
|
存储 Java Unix
Java基础17-读懂Java IO流和常见面试题(一)
Java基础16-读懂Java IO流和常见面试题(一)
49 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),帮助您了解在面试中必备的知识点。这些知识点对于网络编程和系统安全方面的求职者来说至关重要,掌握它们将为您的职业发展打下坚实的基础!
|
11月前
|
Java C++
多线程使用HashMap,HashMap和HashTable和ConcurrentHashMap区别(面试题常考),硬盘IO,顺便回顾volatile(二)
多线程使用HashMap,HashMap和HashTable和ConcurrentHashMap区别(面试题常考),硬盘IO,顺便回顾volatile
|
17天前
|
存储 Java
【IO面试题 四】、介绍一下Java的序列化与反序列化
Java的序列化与反序列化允许对象通过实现Serializable接口转换成字节序列并存储或传输,之后可以通过ObjectInputStream和ObjectOutputStream的方法将这些字节序列恢复成对象。
|
17天前
|
XML 存储 JSON
【IO面试题 六】、 除了Java自带的序列化之外,你还了解哪些序列化工具?
除了Java自带的序列化,常见的序列化工具还包括JSON(如jackson、gson、fastjson)、Protobuf、Thrift和Avro,各具特点,适用于不同的应用场景和性能需求。