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版
Path path = Paths.get("nio-demo/hello.txt");
// 检查文件是否存在
if (Files.notExists(path)) {
// 检查目录是否存在
if (Files.notExists(path.getParent())) {
// 递归创建目录
Files.createDirectories(path.getParent());
}
Files.createFile(path);
}
File、OutputStream版
File file = new File("nio-demo/hello.txt");
// 检查目录是否存在,不存在就创建
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
// 打开文件输出流,会自动创建文件
FileOutputStream outputStream = new FileOutputStream(file);
拼接两个byte[]的方法
byte[] firstBs = "hello ".getBytes();
byte[] secondBs = "world".getBytes();
byte[] newBs = Arrays.copyOf(firstBs, firstBs.length + secondBs.length);
// 此处可以替换为某个读取方法
System.arraycopy(secondBs, 0, newBs, firstBs.length, secondBs.length);
遍历目录的两种方式
Path path = Paths.get("files");
// 第一种:只能遍历当前目录下的目录和文件,不能递归遍历
try (DirectoryStream<Path> entries = Files.newDirectoryStream(path, "*")) {
for (Path entity : entries) {
System.out.println(entity.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
// 第二种:可以递归遍历到所有文件,但是遍历不到目录
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println(file);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}