JavaScript 讀寫文件 實(shí)現(xiàn)教程

字號:


    <script>
    /*
    object.OpenTextFile(filename[, iomode[, create[, format]]])
    參數(shù)
    object
    必選項(xiàng)。object 應(yīng)為 FileSystemObject 的名稱。
    filename
    必選項(xiàng)。指明要打開文件的字符串表達(dá)式。
    iomode
    可選項(xiàng)。可以是三個(gè)常數(shù)之一:ForReading 、 ForWriting 或 ForAppending 。
    create
    可選項(xiàng)。Boolean 值,指明當(dāng)指定的 filename 不存在時(shí)是否創(chuàng)建新文件。如果創(chuàng)建新文件則值為 True ,如果不創(chuàng)建則為 False 。如果忽略,則不創(chuàng)建新文件。
    format
    可選項(xiàng)。使用三態(tài)值中的一個(gè)來指明打開文件的格式。如果忽略,那么文件將以 ASCII 格式打開。
    設(shè)置
    iomode 參數(shù)可以是下列設(shè)置中的任一種:
    常數(shù) 值 描述
    ForReading 1 以只讀方式打開文件。不能寫這個(gè)文件。
    ForWriting 2 以寫方式打開文件
    ForAppending 8 打開文件并從文件末尾開始寫。
    format 參數(shù)可以是下列設(shè)置中的任一種:
    值 描述
    TristateTrue 以 Unicode 格式打開文件。
    TristateFalse 以 ASCII 格式打開文件。
    TristateUseDefault 使用系統(tǒng)默認(rèn)值打開文件。
    */
    //讀文件
    function readFile(filename){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var f = fso.OpenTextFile(filename,1);
    var s = "";
    while (!f.AtEndOfStream)
    s += f.ReadLine()+"/n";
    f.Close();
    return s;
    }
    //寫文件
    function writeFile(filename,filecontent){
    var fso, f, s ;
    fso = new ActiveXObject("Scripting.FileSystemObject");
    f = fso.OpenTextFile(filename,8,true);
    f.WriteLine(filecontent);
    f.Close();
    alert('ok');
    }
    </script>
    <html>
    <input type="text" id="in" name="in" />
    <input type="button" value="Write!" onclick="writeFile('c:/12.txt',document.getElementById('in').value);"/><br><br>
    <input type="button" value="Read!" onclick="document.getElementById('show').value=readFile('c:/12.txt');"/><br>
    <textarea id="show" name="show" cols="50" rows="8" >
    </textarea>
    </html>