package yelp.dataset.oswego.yelpbackend.services; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import lombok.NoArgsConstructor; import yelp.dataset.oswego.yelpbackend.algorithms.btree.BusinessBtree; @NoArgsConstructor public class IOUtil { private final String fileDest = "YOUR PATH TO FILE"; protected void writeFileWithFileChannel(BusinessBtree businessBtree) throws IOException { // Get the file FileOutputStream fout = new FileOutputStream(fileDest); // Register FileChannel to operate read and write FileChannel wChannel = fout.getChannel(); // Register ByteBuffer to store message inside a buffer ByteBuffer wBuffer = ByteBuffer.allocate(1024); String message = "Writing on disk"; wBuffer.put(message.getBytes()); /* ByteBuffer::flip() is used to flip BB from "reading from I/O"(put) to "writing to I/O"(get) after a sequence of put ByteBuffer::flip() will set the limit of the buffer to current position and reset the position to 0 */ wBuffer.flip(); // Acctually write to file from buffer wChannel.write(wBuffer); System.out.println("Success!"); } protected void readRootWithFileChannel(BusinessBtree businessBtree) throws IOException { // Get the file RandomAccessFile raf = new RandomAccessFile(bTreeRoot, "rw"); // Register FileChannel to operate read and write FileChannel fChannel = raf.getChannel(); // Allocaate bufferSize int bufferSize = 1024; if (bufferSize > fChannel.size()) { bufferSize = (int) fChannel.size(); } // Register ByteBuffer to store message inside a buffer ByteBuffer buff = ByteBuffer.allocate(bufferSize); // Read the file to buffer fChannel.read(buff); // Flip the buffer buff.flip(); System.out.println("Reading from buffer = " +new String(buff.array())); } protected void readRootWithPath(BusinessBtree businessBtree) throws IOException { Path path = Paths.get(bTreeRoot); List read = Files.readAllLines(path); System.out.println("Files.readAllLines(path) = " + read); Stream lines = Files.lines(path); String data = lines.collect(Collectors.joining(" + ")); lines.close(); System.out.println("Files.lines(path) = " +data); } public class WriteExample { public static void main(String... args) throws IOException { Path path = Files.createTempFile("test-file", ".txt"); Files.write(path, "some test content...".getBytes()); byte[] bytes = Files.readAllBytes(path); System.out.println(new String(bytes)); } } public class WriteIterable { public static void main(String... args) throws IOException { Path path = Files.createTempFile("test-file", ".txt"); Iterable iterable = Arrays.asList("line1", "line2"); Files.write(path, iterable); byte[] bytes = Files.readAllBytes(path); System.out.println(new String(bytes)); } }