Java资料读写核心代码
Java文件读写核心代码
//创建一个文件 File file=new File("E:\\c.txt"); FileInputStream inputStream=new FileInputStream(file.getAbsolutePath()); FileOutputStream outputStream=new FileOutputStream("E:\\d.txt"); byte[] b=new byte[2048]; int readByte=0; //inputStream读取文件流 //将读的的信息放入byte[]b数组中 while((readByte=inputStream.read(b))>0) { //readByte:读取到的字节数 outputStream.write(b, 0, readByte); } //关闭读取 outputStream.close(); inputStream.close();
说明:
readByte=inputStream.read(b):
1.从此输入流中将最多 b.length
个字节的数据读入一个 byte 数组中
2.返回值(readByte):读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1
使用新IO中的Channel方式读写文件
FileChannel fci = new FileInputStream("e:\\yang.iso").getChannel(); FileChannel fco = new FileOutputStream("e:\\gao.iso").getChannel(); ByteBuffer bf = ByteBuffer.allocate(2048); while(fci.read(bf) != -1){ bf.flip(); fco.write(bf); bf.clear(); } fco.close(); fci.close();
说明:nio中方法好像比io中的更简洁,且更快!