下面是测试代码,实际情况请以业务需求为准
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Test
public void contextLoads() {
}
@Test
public void nIOReadTextFile() {
String filePath = "C:\\Users\\virgil\\Desktop\\新建文本文档.txt";
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(filePath, "rw");
FileChannel fileChannel = randomAccessFile.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int read = fileChannel.read(byteBuffer);
while (read != -1) {
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
System.out.print((char) byteBuffer.get());
}
byteBuffer.compact();
read = fileChannel.read(byteBuffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (randomAccessFile != null) {
randomAccessFile.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
@Test
public void nioCopyFileTest() {
// nioCopyFile("G:\\nIO Copy\\1.txt", "G:\\nIO Copy\\2.txt");
nioCopyFile("C:\\Users\\virgil\\Pictures\\Saved Pictures\\616ad2a19e4ac0d5ad82530e0b00101a.jpg", "G:\\nIO Copy\\1.jpg");
}
public void nioCopyFile(String readFilePath, String copyFileEndPath) {
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
inChannel = new FileInputStream(new File(readFilePath)).getChannel();
outChannel = new FileOutputStream(new File(copyFileEndPath)).getChannel();
int maxCount = (64 * 1024 * 1024) - (32 * 1024);
long size = inChannel.size();
long position = 0;
while (position < size) {
position += inChannel.transferTo(position, maxCount, outChannel);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inChannel != null) {
inChannel.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (outChannel != null) {
outChannel.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}