var TxtFile = function(ClassName)
{
this.ClassName = ClassName
this.Fso = null
this.Delay = 10000//多长时间读取一次
this.ReadLine = 0//睁埋初始化告早冲,从第几行开始读取
this.RowCount = 1//文本的总行数
this.TxtContent = null//文本的内容,数组
this.ForReading = 1//只读
}
TxtFile.prototype.CreateObject = function()
{
if(this.Fso == null)
{
this.Fso = new ActiveXObject("袜歼Scripting.FileSystemObject")
}
}
TxtFile.prototype.OpenFile = function(TxtFilePath)
{
this.CreateObject()
try
{
var f = this.Fso.OpenTextFile(TxtFilePath,this.ForReading)
}
catch (e)
{
alert("文件不存在")
return
}
if(f.AtEndOfLine)
{
alert('空文件!')
this.RowCount = 1
this.TxtContent = [""]
}
else
{
this.TxtContent = f.ReadAll().split("\r\n")
this.RowCount = this.TxtContent.length
}
this.ToAlertFileConten()
}
TxtFile.prototype.ToAlertFileConten = function()
{
if(this.ReadLine <this.RowCount )
{
alert(this.TxtContent[this.ReadLine])
}
if(this.ReadLine ==this.RowCount - 1)
{
alert("文件读取完毕。")
}
else
{
this.ReadLine++
window.setTimeout(""+ this.ClassName +".ToAlertFileConten()",this.Delay)
}
}
var MyTxtFile = new TxtFile("MyTxtFile")
MyTxtFile.OpenFile("c:\\temp.txt")
</script>
解决方法:
1、通过IE的FSO方法,不过该方法只有IE中可以使用
2、通过Ajax方式读取文本铅睁,该方法通用,建议使用该方法
代码示例:
$(document).ready(function(){$("#b01").click(function(){//比如再按钮的单击事件中
htmlobj=$.ajax({url:"/jquery/test1.txt",async:false})//通过ajax读取test1.txt文本文件。
$("#myDiv").html(htmlobj.responseText.replace(/.+/g,'</br>'))//根据回车换行符凯升进行替换,替换成html换行符<br>
})
})
<div id='myDiv'></div>
<input type='button'槐孙岁 id='b01' value='读取文本'/>
下面的代码仅做了读培拆取指定行测试在使用.hta测配信枣试可行 核心代码如下:
function readLine(){
var line=document.all("line").value||0 //获取指定行号默认为从第一行 0 行开始
f = fso.OpenTextFile("D:\\txt.txt", ForReading)
for(var i=0i<linei++){
f.SkipLine() //跳过指定行
}
r=f.ReadLine() //读到目标行
document.all("txtBox").innerText=r
//输坦者出结果
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)