Java Reference
In-Depth Information
// Get the file encoding for the system
String encoding = System.getProperty("file.encoding");
Charset cs = Charset.forName(encoding);
try (SeekableByteChannel seekableChannel =
Files.newByteChannel(src,
READ, WRITE, CREATE, TRUNCATE_EXISTING)) {
// Print the details
printDetails(seekableChannel, "Before writing data");
// First, write some data to the file
writeData(seekableChannel, cs);
// Print the details
printDetails(seekableChannel, "After writing data");
// Reset the position of the seekable channel to 0,
// so we can read the data from the beginning
seekableChannel.position(0);
// Print the details
printDetails(seekableChannel,
"After resetting position to 0");
// Read the data from the file
readData(seekableChannel, cs);
// Print the details
printDetails(seekableChannel, "After reading data");
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void writeData(SeekableByteChannel seekableChannel,
Charset cs) throws IOException {
// Get the platform-dependent line separator
String separator = System.getProperty("line.separator");
// Prepare the text to write to the file
StringBuilder sb = new StringBuilder();
sb.append("When the blazing sun is gone,");
sb.append(separator);
sb.append("When he nothing shines upon,");
sb.append(separator);
sb.append("Then you show your little light,");
sb.append(separator);
sb.append("Twinkle, twinkle, all the night");
sb.append(separator);
Search WWH ::




Custom Search