当前位置:软件学堂 > 资讯首页 > 网络编程 > 编程其他 > 使用FS0读写文本文件

使用FS0读写文本文件

2012/11/11 12:25:07作者:佚名来源:网络

移动端

【实例名称】

使用FS0读写文本文件

【实例描述】

文件操作是网页中常用的数据处理方法,有时可以将网页内容保存到文本文件或XML文件中。本例学习如何使用JaVascript操作文本文件。

【实例代码】

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>pubs-学无忧(www.xue51.com)</title> <style>  table {   border:2 groove black;   position:absolute;   top:10;   left:10;  }  td {   border:1 ridge blue;  } </style> </head> <script language="Javascript">  var path="c:\\";      //文件路径  var fname="test.txt"  //文件名  window.status="邮件信息"; //状态栏信息  function getFileName(){   if (txtFile.value != "" && txtFile.value != " ") //如果用户不输入文件名    fname=txtFile.value;         //使用默认文件名  }  function saveFile(){           //保存文件的方法   var fso,file;   if (txtContent.value == ""){  //判断是否填写了文件内容    alert("请输入文件内容!");    return;   }else{    getFileName();               //获取文件名    fso=new ActiveXObject("Scripting.FileSystemObject"); //创建文件对象    file = fso.CreateTextFile(path + fname,true);       //指定文件详细路径    file.WriteLine(txtContent.value);                   //输出文件内容    file.close();          //关闭文件写入流    alert("保存完毕!");   }  }  function readFile(){             //读取文件的方法   var fso,str,file;   getFileName();   fso = new ActiveXObject("Scripting.FileSystemObject"); //创建文件对象   str = "文件内容为空";   if (fso.FileExists(path + fname)){               //判断文件是否存在    file=fso.OpenTextFile(path + fname,1);          //打开文件    str=file.readall();         //读取文件所有内容    file.close();     //关闭文件读取流   }   txtContent.value = str; //显示文件内容  }

</script> <body> <table width="437" height="157" border="0" align="center" cellpadding="0" cellspacing="0">   <tr>     <td width="433" height="28">文件名:       <input type="text" id="txtFile">    <button name="save" onClick="Javascript:saveFile()">保存</button>    <button name="read" onClick="Javascript:readFile()">读取</button>     </td>   </tr>   <tr>     <td height="23"><div align="center">文件内容</div></td>   </tr>   <tr>     <td><textarea name="txtContent" rows="18" cols="60"> </textarea></td>   </tr> </table> </body> </html>

 

【运行效果】

 使用FS0读写文本文件运行效果

【难点剖析】

本例的难点是如何使用操作文件的“Scripting.FileSystemObject”组件。此组件就是常说的FSO对象,用于在JavaScript中处理文件。此对象的“CreateTextFile”方法用来创建文件,注意创建文件时需要指定文件的绝对路径。“OpenTextFile”方法用来打开文件也需要文件的绝对路径。“WriteLine”方法用来写内容到文件。“readall”方法用来读取文件内容。

【源码下载】

为了JS代码的准确性,请点击:使用FS0读写文本文件 进行本实例源码下载