7.6 写入文件

优质
小牛编辑
128浏览
2023-12-01

通过FileEntry的createWriter方法可以获取FileWriter对象,通过FileWriter可以对文件进行写操作:

fileEntry.createWriter(function(fileWriter) {
    //We'll do something with fileWriter later
}, errorHandler);

对于FileEntry,可以通过Entry的getFile方法获取,也可以直接通过指定saveFile类型的chooseEntry获得:

chrome.fileSystem.chooseEntry({type: 'openDirectory'}, function(Entry) {
    Entry.getFile('log.txt', {}, function(fileEntry) {
        fileEntry.createWriter(function(fileWriter) {
            //We'll do something with fileWriter later
        }, errorHandler);
    }, errorHandler);
});

chrome.fileSystem.chooseEntry({
    type: 'saveFile',
    suggestedName: 'log.txt'
}, function(fileEntry) {
    fileEntry.createWriter(function(fileWriter) {
        //We'll do something with fileWriter later
    }, errorHandler);
});

由于之后的操作都是针对FileWriter的,下面将只讲解与FileWriter相关的内容。