文件通道定义了两个方法,可以进行直接的文件传输:
int transferTo(int position,long count,WritableByteChannel dst);
这个函数是把文件从position位置开始向dst通道传送count个字节。
int transferFrom(ReadableByteChannel src,long position,long count);
将count个字节从通道src传送到文件中,position是为文件开始写入的位置。
从FileInputStream中获得的通道只支持transferTo,而从FileOutputStream中获得的通道只支持tansferFrom()方法
1. FileChannel sfc = new FileInputStream(“D:\\suqiang\\from.txt”).getChannel();
2. FileChannel tfc = new FileOutputStream(“D:\\suqiang\\to.txt”).getChannel();
3. sfc.transferTo(0, sfc.size(), tfc);
4. sfc.close();
5. tfc.close();
做开发的经常碰到文件的操作,特别是文件的“读”操作。在java中,读文件有很多种方法,有FileReader、BufferReader等,当然,各种方法的效率是不一样的,FileReader经BufferReader包装后效率明显提高,在个别时候,我们可以用java.nio包进行文件操作,如下:
private static String fileReader(File fileName) {
String fileContent = null;
FileInputStream fis = null;
FileChannel fc = null;
try {
fis = new FileInputStream(fileName);
// get a file channel
fc = fis.getChannel();
// create a ByteBuffer that is large enough
// and read the contents of the file into it
// test
// System.out.println(fc.size());
ByteBuffer bb = ByteBuffer.allocate((int) fc.size() + 1);
fc.read(bb);
bb.flip();
// save the content of the file as a String
// if we want to change the encode
// we can directly add a second parameter here
// which is of course more efficent
// System.out.println(bb.capacity());
fileContent = new String(bb.array());
} catch (Exception e) {
e.printStackTrace();
} finally {
// release the FileChannel
try {
fc.close();
} catch (Exception ex) {
int transferTo(int position,long count,WritableByteChannel dst);
这个函数是把文件从position位置开始向dst通道传送count个字节。
int transferFrom(ReadableByteChannel src,long position,long count);
将count个字节从通道src传送到文件中,position是为文件开始写入的位置。
从FileInputStream中获得的通道只支持transferTo,而从FileOutputStream中获得的通道只支持tansferFrom()方法
1. FileChannel sfc = new FileInputStream(“D:\\suqiang\\from.txt”).getChannel();
2. FileChannel tfc = new FileOutputStream(“D:\\suqiang\\to.txt”).getChannel();
3. sfc.transferTo(0, sfc.size(), tfc);
4. sfc.close();
5. tfc.close();
做开发的经常碰到文件的操作,特别是文件的“读”操作。在java中,读文件有很多种方法,有FileReader、BufferReader等,当然,各种方法的效率是不一样的,FileReader经BufferReader包装后效率明显提高,在个别时候,我们可以用java.nio包进行文件操作,如下:
private static String fileReader(File fileName) {
String fileContent = null;
FileInputStream fis = null;
FileChannel fc = null;
try {
fis = new FileInputStream(fileName);
// get a file channel
fc = fis.getChannel();
// create a ByteBuffer that is large enough
// and read the contents of the file into it
// test
// System.out.println(fc.size());
ByteBuffer bb = ByteBuffer.allocate((int) fc.size() + 1);
fc.read(bb);
bb.flip();
// save the content of the file as a String
// if we want to change the encode
// we can directly add a second parameter here
// which is of course more efficent
// System.out.println(bb.capacity());
fileContent = new String(bb.array());
} catch (Exception e) {
e.printStackTrace();
} finally {
// release the FileChannel
try {
fc.close();
} catch (Exception ex) {