陕西建设网官方网站/常用的网络营销工具
文章目录
- RandomAccessFile类
- NIO
RandomAccessFile类
直接继承于Object类,并且实现了DataInput、DataOutput两个接口,意味着这两个类既可以读也可以写
支持随机访问的方式,程序可以直接跳到文件任意地方来读、写文件。
- 支持只访问文件的部分内容
- 可以在已存在的文件后追加内容
RandomAccessFile对象包含一个记录指针,标识当前读写处的位置,此类对象可以自由移动记录指针:
- long getFilePointer():获取文件记录的当前位置
- void seek(long pos):将文件记录指针定义到pos位置
import org.junit.Test;import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;public class RandomAccessFileTest {@Testpublic void test1() throws IOException {RandomAccessFile raf1=null;RandomAccessFile raf2=null;try {raf1=new RandomAccessFile(new File("1.jpg"),"r");//mode:r,rw,rwd同步文件内容的更新,rws同步文件内容和元数据的更新raf2=new RandomAccessFile(new File("1.jpg"),"rw");byte[] buffer=new byte[1024];int len;while((len=raf1.read(buffer))!=-1){raf2.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {if(raf1!=null) raf1.close();if(raf2!=null) raf2.close();}}@Testpublic void test2(){RandomAccessFile raf1=null;try {raf1=new RandomAccessFile("hello.txt","rw");//实现对文件内容进行插入(其实是个覆盖)raf1.seek(3);byte[] buffer=new byte[20];int len;//保存指针3后面的所有内容倒StringBuilder中StringBuilder builder=new StringBuilder((int)new File("hello.txt").length());while ((len=raf1.read(buffer))!=-1) {builder.append(new String(buffer,0,len));}//调回指针,写入xyzraf1.seek(3);raf1.write("xyz".getBytes());//将StringBuilder中的数据写入到文件中raf1.write(builder.toString().getBytes());raf1.close();raf1.write("xyz".getBytes());raf1.close();//写出的文件存在,则从开头位置对原有文件进行覆盖(只能覆盖)} catch (IOException e) {e.printStackTrace();} finally {if(raf1!=null) {try {raf1.close();} catch (IOException e) {e.printStackTrace();}}}}
}
ps.
RandomAccessFile类可以实现多线程断点下载功能,下载前建立两个临时文件,一个是与被下载文件大小相同的空文件,另一个是记录文件指针的位置文件,每次暂停的时候,都会保存上一次指针
NIO
NIO面向缓冲区,IO面向流 因此更加高效
NIO两套:针对标准输入输出的NIO,网络编程OIO
FileChannel
SocketChannel
…
NIO.2 —JDK7
引入Path,可以看做是File类的升级版本
Path path=Paths.get(“index.html”)
利用静态的get方法获取Path对象