javascript如何调用txt数据到需要的变量中

JavaScript012

javascript如何调用txt数据到需要的变量中,第1张

写入 

FileSystemObject可以将文件翻译成文件流。 

第一步: 

例: Var fso=new ActiveXObject(Scripting.FileSystemObject)

创建一个可以将文件翻译成文件流的对象。 

第二步:用于创建一个textStream 对象 

括号里边有三个属性 

1. 文件的绝对路径 

2. 文件的常数 只读=1,只写=2 ,追加=8 等权限。(ForReading 、 ForWriting 或 ForAppending 。); 

3. 一个布尔值 允许新建则为true 相反为false; 

例: Var f=fso.createtextfile(“C:\a.txt”,2,true)

第三步:调用textStream的方法 

1. Write(不在写入数据末尾添加新换行符) 

2. WriteLine(要在最后添加一个新换行符) 

3. WriteBlankLines(增加一个或者多个空行) 

例: f.writeLine(“wo shi di yi hang”)

第四步: 

关闭textStream 对象: 

例:f.close() 

2. 读取 

第一步: Var fso=new ActiveXObject(Scripting.FileSystemObject)

创建一个可以将文件翻译成文件流的对象。 

第二步:用于创建一个textStream 对象 

括号里边有三个属性 

4. 文件的绝对路径 

5. 文件的常数 只读=1,只写=2 ,追加=8 等权限。(ForReading 、 ForWriting 或 ForAppending 。); 

6. 一个布尔值 允许新建则为true 相反为false; 

例: Var f=fso.opentextfile(“C:\a.txt”,1,true)

第三步:调用读取方法 

1. Read(用于读取文件中指定数量的字符) 

2. ReadLine(读取一整行,但不包括换行符) 

3. ReadAll(则读取文本文件的整个内容); 

判断是否读取到最后一行

第四步: 

关闭textStream 对象: 

例:f.close() 

可以读取的,给你一个例子 自动写入和读取 D://js读取文本文件.txt

注意 只能在IE模式使用

<html>

<meta http-equiv="content-type" content="text/htmlcharset=gbk" />

<head>

<script language="javascript" type="text/javascript">

//读文件

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>

</head>

<body>

该例子 将文件保存在D盘 D://js读取文本文件.txt

<input type="text" id="in" name="in" />

<input type="button" value="保存" onClick="writeFile('D://js读取文本文件.txt', document.getElementById('in').value)"/>

<br>

<br>

<input type="button" value="读取" onClick="document.getElementById('show').value=readFile('D://js读取文本文件.txt')"/>

<br>

<textarea id="show" name="show" cols="100″ rows="20″ ></textarea>

</body>

</html>