NIO:
package org.test.file.nio;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
public class NioTest {
public static void main(String[] args) {
String ressult = readFile("D:\\temp\\testFile.txt");
System.out.println(ressult);
boolean writeRessult = writeToFile("new write file:" + System.lineSeparator() + ressult,
"D:\\temp\\testFileWt.txt");
System.out.println("write to file result:" + writeRessult);
}
public static String readFile(String filePath) {
StringBuilder sb = new StringBuilder();
try {
// 使用jdk1.7+的try with resource 语句,无需进行资源释放
try (RandomAccessFile ra = new RandomAccessFile(new File(filePath), "r");
FileChannel channel = ra.getChannel()) {
ByteBuffer cb = ByteBuffer.allocate(512);
while (channel.read(cb) != -1) {
sb.append(new String(cb.array(), "UTF-8"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public static boolean writeToFile(String content, String filePath) {
try {
// 使用jdk1.7+的try with resource 语句,无需进行资源释放
try (RandomAccessFile raf = new RandomAccessFile(new File(filePath), "rw");
FileChannel fc = raf.getChannel()) {
ByteBuffer bf = ByteBuffer.wrap(content.getBytes(Charset.forName("UTF-8")));
fc.write(bf);
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}