1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
| package com.holelin.sundry.test.io;
import com.google.common.io.ByteStreams; import com.google.common.io.LineProcessor; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test;
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.io.Writer; import java.net.URL; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream;
public class NIOTest {
public static final String SMALL_FILE_PATH = "/Users/holelin/Downloads/手术-示例报文.txt"; public static final String LARGE_FILE_PATH = "/Users/holelin/Downloads/win11-22000-arm64.ISO"; public static final String DEMO_FILE_PATH = "/Users/holelin/Downloads/demo.txt"; public static final String RENAME_FILE_PATH = "/Users/holelin/Downloads/demo2.txt"; public static final String MOVE_FILE_PATH = "/Users/holelin/demo2.txt"; public static final String READ_ONLY_FILE_PATH = "/Users/holelin/Downloads/read_only.txt"; public static final String fileName = "bootstrap.yml"; public static final String DIR = "/Users/holelin/Downloads";
@Test public void readSmallFile() throws IOException { try (RandomAccessFile aFile = new RandomAccessFile(SMALL_FILE_PATH, "r"); FileChannel inChannel = aFile.getChannel();) {
long fileSize = inChannel.size();
ByteBuffer buffer = ByteBuffer.allocate((int) fileSize); inChannel.read(buffer); buffer.flip();
for (int i = 0; i < fileSize; i++) { System.out.print((char) buffer.get()); } } catch (IOException e) { e.printStackTrace(); } }
@Test public void readLargeFile() { try (RandomAccessFile aFile = new RandomAccessFile(SMALL_FILE_PATH, "r"); FileChannel inChannel = aFile.getChannel();) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (inChannel.read(buffer) > 0) { buffer.flip(); for (int i = 0; i < buffer.limit(); i++) { System.out.print((char) buffer.get()); } buffer.clear(); } } catch (IOException e) { e.printStackTrace(); } }
@Test public void readUsingMappedByteBuffer() { try (RandomAccessFile aFile = new RandomAccessFile(SMALL_FILE_PATH, "r"); FileChannel inChannel = aFile.getChannel();) {
MappedByteBuffer buffer = inChannel .map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
buffer.load(); for (int i = 0; i < buffer.limit(); i++) { System.out.print((char) buffer.get()); } buffer.clear();
} catch (IOException e) { e.printStackTrace(); } }
@Test public void writeUsingChannel() { Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try ( RandomAccessFile stream = new RandomAccessFile(filePath.toFile(), "rw"); FileChannel channel = stream.getChannel();) {
byte[] strBytes = content.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes); buffer.flip(); channel.write(buffer); } catch (Exception e) {
} }
@Test public void writeUsingFileOutputStream() { Path filePath = Path.of("demo.txt"); String content = "hello world !!1";
try (FileOutputStream outputStream = new FileOutputStream(filePath.toFile())) {
byte[] strToBytes = content.getBytes(); outputStream.write(strToBytes); } catch (Exception e) {
} }
@Test public void outputStreamToInputStream() { try (FileOutputStream fos = new FileOutputStream(new File("/Users/holelin/Projects/MySelf/Java-Notes/sundry/demo.txt")); FileInputStream fis = new FileInputStream(new File("/Users/holelin/Projects/MySelf/Java-Notes/sundry/demo2.txt"));) {
FileChannel outputChannel = fos.getChannel(); FileChannel inputChannel = fis.getChannel();
outputChannel.transferTo(0, inputChannel.size(), inputChannel); } catch (Exception e) {
} }
@Test public void channelTransfer() throws IOException { String[] inputFiles = new String[]{"demo.txt", "demo2.txt", "demo3.txt"};
String outputFile = "outputFile.txt";
FileOutputStream fos = new FileOutputStream(new File(outputFile)); WritableByteChannel targetChannel = fos.getChannel();
for (int i = 0; i < inputFiles.length; i++) { FileInputStream fis = new FileInputStream(inputFiles[i]); FileChannel inputChannel = fis.getChannel();
inputChannel.transferTo(0, inputChannel.size(), targetChannel);
inputChannel.close(); fis.close(); }
targetChannel.close(); fos.close();
}
@Test public void createFile() throws IOException { final Path path = Paths.get(DEMO_FILE_PATH); if (!path.toFile().exists()) { Files.createFile(path); } final Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("r--r--r--"); final FileAttribute<Set<PosixFilePermission>> attribute = PosixFilePermissions.asFileAttribute(permissions); final Path readOnlyPath = Paths.get(READ_ONLY_FILE_PATH); if (!readOnlyPath.toFile().exists()) { Files.createFile(readOnlyPath, attribute); } }
@Test public void readFileToByte() throws IOException { final Path path = Paths.get(SMALL_FILE_PATH); final byte[] bytes = Files.readAllBytes(path);
final File file = new File(SMALL_FILE_PATH); FileInputStream fileInputStream = null; final byte[] bfile = new byte[(int) file.length()]; try { fileInputStream = new FileInputStream(file); fileInputStream.read(bfile); fileInputStream.close(); } catch (Exception e) { e.printStackTrace(); } final byte[] bytes1 = FileUtils.readFileToByteArray(file); final byte[] bytes2 = IOUtils.toByteArray(new FileInputStream(file));
final byte[] bytes3 = com.google.common.io.Files.toByteArray(file); final byte[] bytes4 = ByteStreams.toByteArray(new FileInputStream(file)); }
@Test public void readLines() { final Path path = Paths.get(SMALL_FILE_PATH); try (final Stream<String> lines = Files.lines(path)) { final List<String> filteredLines = lines.filter(s -> s.contains("body")).collect(Collectors.toList()); filteredLines.forEach(System.out::println); } catch (IOException e) { throw new RuntimeException(e); }
File file = new File(SMALL_FILE_PATH); try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }
try { List<String> lines = com.google.common.io.Files.readLines(file, Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); }
LineProcessor<List<String>> lineProcessor = new LineProcessor<>() { final List<String> result = new ArrayList<>();
@Override public boolean processLine(final String line) throws IOException { result.add(StringUtils.capitalize(line)); return true; }
@Override public List<String> getResult() { return result; } };
try { List<String> lines = com.google.common.io.Files .asCharSource(file, Charset.defaultCharset()) .readLines(lineProcessor); } catch (IOException e) { e.printStackTrace(); }
try { List<String> lines = FileUtils.readLines(file, Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } }
@Test public void readFileFromClassPath() throws FileNotFoundException {
final ClassLoader classLoader = getClass().getClassLoader(); final URL resource = classLoader.getResource("bootstrap.yml"); if (Objects.isNull(resource)) { throw new FileNotFoundException("file is not found!"); } else { final File file = new File(resource.getFile()); try { List<String> lines = FileUtils.readLines(file, Charset.defaultCharset()); lines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } }
@Test public void readFileFromResourceDirectory() { final InputStream is = this.getClass().getClassLoader() .getResourceAsStream(fileName); try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr);) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } is.close(); } catch (IOException e) { throw new RuntimeException(e); }
final URL resource = this.getClass().getClassLoader().getResource(fileName); final File file = new File(resource.getFile()); }
@Test public void writeFile() { Path filePath = Path.of(DEMO_FILE_PATH); String content = "hello world !!"; try ( RandomAccessFile stream = new RandomAccessFile(filePath.toFile(), "rw"); FileChannel channel = stream.getChannel();) {
byte[] strBytes = content.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes); buffer.flip(); channel.write(buffer); } catch (Exception e) {
}
content = "hello world !!2"; try (BufferedWriter writer = new BufferedWriter( new FileWriter(filePath.toFile()))) { writer.write(content); } catch (Exception e) {
}
try (FileOutputStream outputStream = new FileOutputStream(filePath.toFile())) { byte[] strToBytes = content.getBytes(); outputStream.write(strToBytes); } catch (IOException e) { throw new RuntimeException(e); }
try (FileOutputStream outputStream = new FileOutputStream(filePath.toFile()); DataOutputStream dataOutStream = new DataOutputStream(new BufferedOutputStream(outputStream));) { dataOutStream.writeUTF(content); dataOutStream.writeInt(10); dataOutStream.writeLong(100L); } catch (IOException e) { throw new RuntimeException(e); } }
@Test public void appendToFile() throws IOException { String textToAppend = "Happy Learning !!"; Path path = Paths.get(DEMO_FILE_PATH); Files.write(path, textToAppend.getBytes(), StandardOpenOption.APPEND);
try (FileWriter fw = new FileWriter(DEMO_FILE_PATH, true); BufferedWriter writer = new BufferedWriter(fw);) {
writer.write(textToAppend); }
try (FileOutputStream outputStream = new FileOutputStream(fileName, true)) {
byte[] strToBytes = textToAppend.getBytes(); outputStream.write(strToBytes); } }
@Test public void writeFileWithEncode() { try (Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(DEMO_FILE_PATH), StandardCharsets.UTF_8))) {
out.append("Test") .append("\r\n") .append("UTF-8 Demo") .append("\r\n") .append("冲冲冲") .append("\r\n");
out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } }
@Test public void moveAndRename() throws IOException {
File originalFile = new File(DEMO_FILE_PATH); File renamedFile = new File(RENAME_FILE_PATH); File movedFile = new File(MOVE_FILE_PATH); final boolean b = originalFile.renameTo(renamedFile); final boolean b1 = renamedFile.renameTo(movedFile);
final Path path = Path.of(DEMO_FILE_PATH); Files.move(path, path.resolveSibling("test.txt"));
FileUtils.moveFile(originalFile, renamedFile); File targetDirectory = new File(DEMO_FILE_PATH); FileUtils.moveFileToDirectory(originalFile, targetDirectory, true); }
@Test public void copyFile() throws IOException { final Path source = Paths.get(DEMO_FILE_PATH); final Path target = Paths.get(source.resolveSibling("test.txt").toString()); Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
final File file = source.toFile(); final FileInputStream sourceInputStream = new FileInputStream(file); final FileChannel inChannel = sourceInputStream.getChannel(); final FileOutputStream targetOutputStream = new FileOutputStream(target.toFile()); final FileChannel outChannel = targetOutputStream.getChannel();
inChannel.transferTo(0, file.length(), outChannel); sourceInputStream.close(); targetOutputStream.close();
}
@Test public void deleteFile() throws IOException { final Path path = Paths.get(DEMO_FILE_PATH); final File file = path.toFile();
Files.delete(path); Files.deleteIfExists(path);
FileUtils.delete(file); FileUtils.deleteQuietly(file); FileUtils.deleteDirectory(new File("/Users/holelin/Downloads/a")); }
@Test public void fileSize() throws IOException { final Path path = Paths.get(DEMO_FILE_PATH); final long size = Files.size(path); System.out.println(size); final long sizeOf = FileUtils.sizeOf(path.toFile()); System.out.println(FileUtils.byteCountToDisplaySize(sizeOf)); } @Test public void readDir() throws IOException { Path path = Paths.get(DIR); AtomicInteger dirCount = new AtomicInteger(); AtomicInteger fileCount = new AtomicInteger(); Files.walkFileTree(path, new SimpleFileVisitor<Path>(){ @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { System.out.println(dir); dirCount.incrementAndGet(); return super.preVisitDirectory(dir, attrs); }
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println(file); fileCount.incrementAndGet(); return super.visitFile(file, attrs); } }); System.out.println(dirCount); System.out.println(fileCount); }
public static void recursionDeleteDirectory(Path dirPath) throws IOException { Assert.isTrue(Objects.nonNull(dirPath), "目录不能为空"); Assert.isTrue(dirPath.toFile().isDirectory(), "路径不为目录"); Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); log.debug("文件被删除:{}", file); return FileVisitResult.CONTINUE; }
@Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); log.debug("文件夹被删除:{}", dir); return FileVisitResult.CONTINUE; } } ); } }
|