Java经典IO类选择向导

| 数据类型 | 基于字节的 Input | 基于字节的 Output | 基于字符的 Input | 基于字符的 Output | | 基础 | InputStream | OutputStream | Reader
InputStreamReader | Writer
OutputStreamWriter | | —- | —- | —- | —- | —- | | 数组 | ByteArrayInputStream | ByteArrayOutputStream | CharArrayReader | CharArrayWriter | | Files | FileInputStream
RandomAccessFile | FileOutputStream
RandomAccessFile | FileReader | FileWriter | | 管道 | PipedInputStream | PipedOutputStream | PipedReader | PipedWriter | | 缓冲 | BufferedInputStream | BufferedOutputStream | BufferedReader | BufferedWriter | | 过滤 | FilterInputStream | FilterOutputStream | FilterReader | FilterWriter | | 解析 | PushbackInputStream
StreamTokenizer | | PushbackReader
LineNumberReader | | | 字符串 | | | StringReader | StringWriter | | 数据 | DataInputStream | DataOutputStream | | | | 数据
(格式化) | | PrintStream | | PrintWriter | | 对象 | ObjectInputStream | ObjectOutputStream | | | | 组合多个流 | SequenceInputStream | | | |

创建目录及文件

Path、Files版

  1. Path path = Paths.get("nio-demo/hello.txt");
  2. // 检查文件是否存在
  3. if (Files.notExists(path)) {
  4. // 检查目录是否存在
  5. if (Files.notExists(path.getParent())) {
  6. // 递归创建目录
  7. Files.createDirectories(path.getParent());
  8. }
  9. Files.createFile(path);
  10. }

File、OutputStream版

  1. File file = new File("nio-demo/hello.txt");
  2. // 检查目录是否存在,不存在就创建
  3. if (!file.getParentFile().exists()) {
  4. file.getParentFile().mkdirs();
  5. }
  6. // 打开文件输出流,会自动创建文件
  7. FileOutputStream outputStream = new FileOutputStream(file);

拼接两个byte[]的方法

  1. byte[] firstBs = "hello ".getBytes();
  2. byte[] secondBs = "world".getBytes();
  3. byte[] newBs = Arrays.copyOf(firstBs, firstBs.length + secondBs.length);
  4. // 此处可以替换为某个读取方法
  5. System.arraycopy(secondBs, 0, newBs, firstBs.length, secondBs.length);

遍历目录的两种方式

  1. Path path = Paths.get("files");
  2. // 第一种:只能遍历当前目录下的目录和文件,不能递归遍历
  3. try (DirectoryStream<Path> entries = Files.newDirectoryStream(path, "*")) {
  4. for (Path entity : entries) {
  5. System.out.println(entity.toString());
  6. }
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. // 第二种:可以递归遍历到所有文件,但是遍历不到目录
  11. try {
  12. Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
  13. @Override
  14. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
  15. System.out.println(file);
  16. return FileVisitResult.CONTINUE;
  17. }
  18. });
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }