<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>js操作文件(ie可用)</title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> <script language="JavaScript"> var fileDir=‘‘; $(document).ready(function(){ fileDir=getFileDir(); $(‘#fileDir‘).html(fileDir); readInfo(); }); /**获取当前文件位置**/ function getFileDir(){ var curRequestPath = window.document.location.href; var decode=decodeURI(curRequestPath); var dir=decode.substring(‘file:///‘.length,decode.lastIndexOf("/")+1); return dir; } /**读取文件**/ function readInfo(){ var fileName=fileDir+$(‘#fileName‘).val(); if(fileName==""){ alert(‘文件名称不能为空‘); return; }else{ var fso,f,ts,s; var ForRWA=0,ForReading=1,ForWriting=2,ForAppending=8; var TristateUseDefault=-2,TristateTrue=-1,TristateFalse=0; fso=new ActiveXObject("Scripting.FileSystemObject"); f=fso.GetFile(fileName); ts=f.OpenAsTextStream(ForReading,TristateUseDefault); try{ s=ts.ReadAll(); }catch(e){} ts.Close(); $(‘#showArea‘).val(s); $(‘#editArea‘).val(s); alert(‘操作成功‘); } } /**写入文件**/ function writeInfo(){ var fileName=fileDir+$(‘#fileName‘).val(); if(fileName==""){ alert(‘文件名称不能为空‘); return; }else{ var content=$(‘#editArea‘).val(); if(content==""){ alert(‘写入内容不能为空‘); } var ForRWA=0,ForReading=1,ForWriting=2; var TristateUseDefault=-2,TristateTrue=-1,TristateFalse=0; fso=new ActiveXObject("Scripting.FileSystemObject"); f=fso.GetFile(fileName); ForRWA=ForWriting; ts=f.OpenAsTextStream(ForRWA,TristateUseDefault); ts.Write(content); ts.Close(); $(‘#showArea‘).val(content); alert(‘操作成功‘); } } /**创建文件**/ function createInfo(){ var content=$(‘#createArea‘).val(); if(content==""){ alert(‘写入内容不能为空‘); return; } var date = new Date(); var year=date .getFullYear(); //获取完整的年份(4位) var month=date .getMonth()+1; //获取当前月份(0-11,0代表1月) var date=date.getDate(); //获取当前日(1-31) var fileName=fileDir+‘workData_‘+year+‘-‘+month+‘-‘+date+‘.json‘; var fso, tf; fso = new ActiveXObject("Scripting.FileSystemObject"); if(fso.FileExists(fileName)){ alert(‘文件已存在‘); return; } // 创建新文件 tf = fso.CreateTextFile(fileName, true); tf.Write(content); // 关闭文件 tf.Close(); alert(‘操作成功‘); } </script> </head> <body> <table width="100%" border="1"> <tr> <td colspan="3"> <p>文件路径:<span id="fileDir"></span></p> <p>文件名称:<input name="text1" id="fileName" value="workData.json" size="40"></p> </td> </tr> <tr> <td width="30%"> <textarea id="showArea" name="showArea" cols="20" rows="10" style="width:98%"></textarea> </td> <td> <textarea id="editArea" name="editArea" cols="20" rows="10" style="width:98%"></textarea> </td> <td> <textarea id="createArea" name="createArea" cols="20" rows="10" style="width:98%"></textarea> </td> </tr> <tr> <td> <input type="button" value="读取" onclick="readInfo()"> </td> <td> <input type="button" value="写入" onclick="writeInfo()"> </td> <td> <input type="button" value="创建" onclick="createInfo()"> </td> </tr> </table> </body> </html>