Java 檔案任意位置讀寫操作(首尾讀寫都可以)
阿新 • • 發佈:2019-01-23
public static void fileOperationInAnyLocation(String filePath) { Path path = Paths.get(filePath); // To check file exist. if (!path.toFile().exists()) throw new IllegalArgumentException("The file path is not exist."); ByteBuffer buffer = ByteBuffer.allocate(1024); try { FileChannel channel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE); channel.read(buffer, channel.size() - 1000); System.out.println(new String(buffer.array())); ByteBuffer writeBuffer = ByteBuffer.allocate(1024); writeBuffer.put("111111111111".getBytes()); channel.write(writeBuffer, 0); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }