TextStream對象
讀文件
本範例示範如何使用FileSystemObject的OpenTextFile方法來建立一個TextStream物件。 TextStream物件的ReadAll方法會從已開啟的文字檔案中取得內容。
本範例程式碼如下:
<html>
<body>
<p>這就是文字檔案中的文字:</p>
<%
Set fs=Server.CreateObject(Scripting.FileSystemObject)
Set f=fs.OpenTextFile(Server.MapPath(/example/aspe/testread.txt), 1)
Response.Write(f.ReadAll)
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>
本實例運行結果如下:
這就是文字檔案中的文字:
Hello! How are you today?
讀文本文件中的一個部分
本範例示範如何僅讀取一個文字流檔案的部分內容。
本範例程式碼如下:
<html>
<body>
<p>這是從文字檔案讀取的前5 個字元:</p>
<%
Set fs=Server.CreateObject(Scripting.FileSystemObject)
Set f=fs.OpenTextFile(Server.MapPath(testread.txt), 1)
Response.Write(f.Read(5))
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>
本實例運行結果如下:
這是從文字檔案讀取的前5 個字元:
Hello
讀文本文件中的一行
本範例示範如何從一個文字流檔案中讀取一行內容。
本範例程式碼如下:
<html>
<body>
<p>這是從文字檔案讀取的第一行:</p>
<%
Set fs=Server.CreateObject(Scripting.FileSystemObject)
Set f=fs.OpenTextFile(Server.MapPath(testread.txt), 1)
Response.Write(f.ReadLine)
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>
本實例運行結果如下:
這是從文字檔案讀取的第一行:
Hello!
讀取文字檔案的所有行
本範例示範如何從文字流檔案中讀取所有的行。
本範例程式碼如下:
<html>
<body>
<p>這是從文字檔案讀取的所有行:</p>
<%
Set fs=Server.CreateObject(Scripting.FileSystemObject)
Set f=fs.OpenTextFile(Server.MapPath(testread.txt), 1)
do while f.AtEndOfStream = false
Response.Write(f.ReadLine)
Response.Write(<br>)
loop
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>
本實例運行結果如下:
這是從文字檔案中讀取的所有行:
Hello!
How are you today?
略過文字檔的一部分
本範例示範如何在讀取文字流檔案時跳過指定的字元數。
本範例程式碼如下:
<html>
<body>
<p>文字檔中的前4 個字元被略掉了:</p>
<%
Set fs=Server.CreateObject(Scripting.FileSystemObject)
Set f=fs.OpenTextFile(Server.MapPath(testread.txt), 1)
f.Skip(4)
Response.Write(f.ReadAll)
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>
本實例運行結果如下:
文字檔案中的前4 個字元被略掉了:
o! How are you today?
略過文字文件的一行
本範例示範如何在讀取文字流檔案時跳過一行。
本範例程式碼如下:
<html>
<body>
<p>文字檔中的第一行被略掉了:</p>
<%
Set fs=Server.CreateObject(Scripting.FileSystemObject)
Set f=fs.OpenTextFile(Server.MapPath(testread.txt), 1)
f.SkipLine
Response.Write(f.ReadAll)
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>
本實例運行結果如下:
文字檔案中的第一行被略掉了:
How are you today?
傳回行數
本範例示範如何傳回在文字流程檔案中的目前行號。
本範例程式碼如下:
<html>
<body>
<p>這是文字檔案中的所有行(帶有行號):</p>
<%
Set fs=Server.CreateObject(Scripting.FileSystemObject)
Set f=fs.OpenTextFile(Server.MapPath(testread.txt), 1)
do while f.AtEndOfStream = false
Response.Write(Line: & f.Line & )
Response.Write(f.ReadLine)
Response.Write(<br>)
loop
f.Close
Set f=Nothing
Set fs=Nothing
%>
</body>
</html>
本實例運行結果如下:
這是文字檔案中的所有行(帶有行號):
Line:1 Hello!
Line:2 How are you today?
取得列數
本範例示範如何取得在文件中目前字元的列號。
本範例程式碼如下:
<html>