ios讀取文件類和常用方法

字號(hào):


    第一、nsfilehandle
    nsfilemanager類主要對文件的操作(刪除、修改、移動(dòng)、復(fù)制等)
    nsfilehandle類主要對文件的內(nèi)容進(jìn)行讀取和寫入
    第二、nsfilehandle類處理文件的步驟
    創(chuàng)建一個(gè)nsfilehandle對象
    對打開的文件進(jìn)行i/0操作
    關(guān)閉文件
    可以使用nsfilehandle進(jìn)行斷點(diǎn)續(xù)傳
    第三、實(shí)現(xiàn)查找功能的代碼:
    nsstring *homepath=nshomedirectory();
    nsstring *filepath=[homepath stringbyappendingpathcomponent:@desktop/hello.rtf];
    nsfilehandle *filehandle=[nsfilehandle filehandleforreadingatpath:filepath];
    nsuinteger length=[filehandle availabledata].length;
    [filehandle seektofileoffset:length/2];
    nsdata *data=[filehandle readdatatoendoffile];
    nsstring *str=[[nsstring alloc] initwithdata:data encoding:nsutf8stringencoding];
    nslog(@%@,str);
    第四、實(shí)現(xiàn)追加文件代碼:
    nsstring *homepath=nshomedirectory();
    nsstring *filepath=[homepath stringbyappendingpathcomponent:@desktop/hello.rtf];
    nsfilehandle *filehandle=[nsfilehandle filehandleforupdatingatpath:filepath];
    //[filehandle seektoendoffile];
    [filehandle seektofileoffset:10];
    nsstring ;
    nsdata *data=[str datausingencoding:nsutf8stringencoding];
    [filehandle writedata:data];
    [filehandle closefile];
    // insert code here...
    nslog(@hello, world!);
    第五、實(shí)現(xiàn)復(fù)制文件的代碼:
    nsstring *homepath=nshomedirectory();
    nsstring *filepath=[homepath stringbyappendingpathcomponent:@desktop/hello.rtf];
    nsstring *objpath=[homepath stringbyappendingpathcomponent:@desktop/copy.rtf];
    nsfilemanager *filemanager=[nsfilemanager defaultmanager];
    bool success=[filemanager createfileatpath:objpath contents:nil attributes:nil];
    nsfilehandle *writefile=[nsfilehandle filehandleforreadingatpath:filepath];
    nsfilehandle *objfile=[nsfilehandle filehandleforwritingatpath:objpath];
    [objfile readdatatoendoffile];
    nsdata *data=[writefile readdatatoendoffile];
    [objfile writedata:data];
    [writefile closefile];
    [objfile closefile];