如何通过FileChannel进行文件的读写操作
1个回答
展开全部
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChannelDemo { public static void main(String[] args) throws IOException { File in = new File("D:\\in.txt"); File out = new File("D:\\out.txt"); if(in.createNewFile()){ System.out.println("in.txt被创建"); FileOutputStream is = new FileOutputStream(in); byte[] b = "我一定能行的".getBytes(); is.write(b, 0, b.length); } if(out.createNewFile()){ System.out.println("out.txt被创建"); } FileInputStream is = new FileInputStream(in); FileOutputStream os = new FileOutputStream(out); FileChannel fis = is.getChannel(); FileChannel fos = os.getChannel(); ByteBuffer bytedata = ByteBuffer.allocate(100); while(fis.read(bytedata)!= -1){ //通过通道读写交叉进行。 bytedata.flip(); fos.write(bytedata); bytedata.clear(); } fis.close(); fos.close(); is.close(); os.close(); } }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询