ios讀取文件類和常用方法

字號:


    第一、nsfilehandle
    nsfilemanager類主要對文件的操作(刪除、修改、移動、復制等)
    nsfilehandle類主要對文件的內容進行讀取和寫入
    第二、nsfilehandle類處理文件的步驟
    創(chuàng)建一個nsfilehandle對象
    對打開的文件進行i/0操作
    關閉文件
    可以使用nsfilehandle進行斷點續(xù)傳
    第三、實現查找功能的代碼:
    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(@);
    第四、實現追加文件代碼:
    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!);
    第五、實現復制文件的代碼:
    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];