1. FileChannel
还可以使用下面方式进行操作,在FileChannel中有两个特殊方法可以允许我们直接将两个通道相连:
long transferFrom(ReadableByteChannel src, long position, long count);
long transferTo(long position, long count, WriteableByteChannel targets);
另外
java.nio.channels.Channels类中提供了实用方法,可以在通道中产生Reader和Writer
Reader和Writer可以通过 Channels.newReader(); Channels.newWriter();
2. Charset 字符集
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class SimpleChannel {
private static String SOURCE_PATH = "d:/aa/aa.txt";
private static String CLONE_PATH = "d:/bb/bb.txt";
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream(new File(SOURCE_PATH));
FileChannel fcInput = fis.getChannel();
FileOutputStream fos = new FileOutputStream(new File(CLONE_PATH));
FileChannel fcOutput = fos.getChannel();
ByteBuffer dst = ByteBuffer.allocate(1024);
while(true) {
// before read clear()
dst.clear();
if(fcInput.read(dst) == -1) {
break;
}
System.out.print(new String(dst.array()));
// before write flip()
dst.flip();
fcOutput.write(dst);
}
fos.flush();
fcInput.close();
fcOutput.close();
fis.close();
fos.close();
}
}
还可以使用下面方式进行操作,在FileChannel中有两个特殊方法可以允许我们直接将两个通道相连:
long transferFrom(ReadableByteChannel src, long position, long count);
long transferTo(long position, long count, WriteableByteChannel targets);
另外
java.nio.channels.Channels类中提供了实用方法,可以在通道中产生Reader和Writer
Reader和Writer可以通过 Channels.newReader(); Channels.newWriter();
2. Charset 字符集
Charset.forName(charCode).newDecoder().decode(buffer).toString();