articleList

08-IO面试题

2025/03/14 posted in  IO
Tags:  #面试题

代码编写需求:找出某目录下的所有子目录以及子文件并打印到控制台上

public static void main(String[] args) {
    // 找出某目录下的所有子目录以及子文件并打印到控制台上
    List paths = new ArrayList<>();
    getAllFilePaths(new File("/Users/huanglei/work/JavaTest/src/com/company/io"), paths);

    for (String path : paths) {
        System.out.println(path);
    }
}

private static void getAllFilePaths(File filePath, List paths) {
    File[] files = filePath.listFiles();
    if (files == null) {
        return;
    }
    for (File f : files) {
        if (f.isDirectory()) {
            paths.add(f.getPath());
            getAllFilePaths(f, paths);
        } else {
            paths.add(f.getPath());
        }
    }
}

有了解新版的JDK处理IO流吗?编写下基础代码, 从一个txt文本里面,拷贝里面的内容到另外一个txt文本里面

  • JDK7 之后的写法,JDK9 ⼜进⾏了改良,但是变化不⼤,记住下⾯的写法即可
  • 需要关闭的资源只要实现了 java.lang.AutoCloseable,就可以⾃动被关闭
  • try() ⾥⾯可以定义多个资源,它们的关闭顺序是最后在 try() 定义的资源先关闭
try (FileInputStream fis = new FileInputStream("src/com/company/1.txt");
     BufferedInputStream bis = new BufferedInputStream(fis);
     FileOutputStream fos = new FileOutputStream("src/com/company/2.txt");
     BufferedOutputStream bos = new BufferedOutputStream(fos)) {
    int size;
    byte[] buf = new byte[1024];
    while ((size = bis.read(buf)) != -1) {
        bos.write(buf, 0, size);
    }
} catch (Exception e) {
    e.printStackTrace();
}