|           编程(Programming)是编定程序的中文简称,就是让计算机代码解决某个问题,对某个计算体系规定一定的运算方式,使计算体系按照该计算方式运行,并最终得到相应结果的过程。为了使计算机能够理解(understand)人的意图,人类就必须将需解决的问题的思路、方法和手段通过计算机能够理解的形式告诉计算机,使得计算机能够根据人的指令一步一步去工作,完成某种特定的任务。这种人和计算体系之间交流的过程就是编程。 【实例名称】 使用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>
  
 【运行效果】   【难点剖析】 本例的难点是如何使用操作文件的“Scripting.FileSystemObject”组件。此组件就是常说的FSO对象,用于在JavaScript中处理文件。此对象的“CreateTextFile”方法用来创建文件,注意创建文件时需要指定文件的绝对路径。“OpenTextFile”方法用来打开文件也需要文件的绝对路径。“WriteLine”方法用来写内容到文件。“readall”方法用来读取文件内容。 【源码下载】 为了JS代码的准确性,请点击:使用FS0读写文本文件 进行本实例源码下载  
 使用编程语言写的程序,由于每条指令都对应计算机一个特定的基本动作,所以程序占用内存少、执行效率高。 
 |