Scripting.TextStream objects

Source: Internet
Author: User
Tags file system html page readline split string to file
stream| objects


Some methods of FileSystemObject, folder, and file objects are related to creating, reading, or writing files through TextStream objects.
Although the TextStream object is defined as a separate, subordinate object of the FileSystemObject object, we have to use the FileSystemObject object or its subordinate object to create a TextStream object and access the contents of the disk file.

5.5.1 methods for creating TextStream objects
There are three common methods for creating or opening a text file and returning the Textstram object, as shown in table 5-13:
Table 5-13 methods and descriptions for creating TextStream objects
Method
Description

CreateTextFile
(Filename,overwrite,unicode)
Creates a new text file on disk with the specified filename filename, and returns a TextStream object corresponding to the file. If the optional overwrite parameter is set to True, a file of the same name with the same path will be overwritten. The default overwrite is false. If the optional Unicode parameter is set to False, the contents of the file are stored in Unicode format. The default Unicode is False

OpenTextFile
(Filename,iomode,create,format)
Open or create (if not present) a file named filename, and return the TextStream object corresponding to the file. The filename parameter can contain an absolute or relative path. The IOMode parameter describes the type of access required. Allowable values are ForReading (1) (default), ForWriting (2), ForAppending (8). When you write to or append to a file that does not exist, a new file is created if the Create argument is set to true. The default create is false. The format parameter describes the data formatting when you read or write a file. The allowable value is Tristatefalse (0) (default), the description is in ASCII data format, TristateTrue (-1) description is in Unicode data format, Tristateusedefault (-2) indicates that the data uses the system default format

OpenAsTextStream
(Iomode,format)
Opens a specified file and returns a TextStream object that can be used to read, write, or append to the file. The IOMode parameter illustrates the type of access that is required. Allowable values are ForReading (1) (default), ForWriting (2), ForAppending (8). The format parameter describes the data formats for reading and writing files. The allowable value is Tristatefalse (0) (default), the description is in ASCII data format, TristateTrue (-1) description is in Unicode data format, Tristateusedefault (-2) indicates using system default format

The methods listed above differ in the implementations in FileSystemObject, folder, and file objects. As shown in table 5-14:
Table 5-Methods contained in 143 objects
Method
FileSystemObject objects
Folder Object
File Object

CreateTextFile
Yes
Yes
Yes

OpenTextFile
Yes
No
No

OpenAsTextStream
No
No
Yes

Therefore, you can use these methods to create a new text file, or to open an existing file. You can get a TextStream object corresponding to the file, and you can manipulate the file using the properties and methods of the TextStream object.
1. Create a new text file
You can create a new text file by using the CreateTextFile method, or overwrite a file that already exists. The returned TextStream object can be used to read and write files.
First create a FileSystemObject object to create the TextStream object. The following example uses VBScript to create a "normal" (i.e., non-Unicode) file named MyFile.txt, overwriting a file with the same name that already exists:
Set objFSO = Server.CreateObject ("Scripting.FileSystemObject")
Set Objtstream = objFSO.CreateTextFile ("C:textfilesmyfile.txt", True, False)
The same can be accomplished with JScript:
var objFSO = Server.CreateObject (' Scripting.FileSystemObject ');
var objtstream = objFSO.CreateTextFile (' C:textfilesmyfile.txt ', true, false);
Once you create the file, you can use Objtstream, which is a reference to a TextStream object, to manipulate the file.
2. Open a text file that already exists
The OpenTextFile method is used to open an existing text file. It returns a TextStream object that can be used to read or append data to a file.
Again, you first create a FileSystemObject object and then use it to create a TextStream object. The following VBScript program example opens a file named MyFile.txt, ready to read its contents:
Set objFSO = Server.CreateObject ("Scripting.FileSystemObject")
Set Objtstream = objFSO.OpenTextFile ("C:textfilesmyfile.txt", ForReading)
with JScript:
var objFSO = Server.CreateObject (' Scripting.FileSystemObject ');
var objtstream = objFSO.OpenTextFile (' c:textfilesmyfile.txt ', ForReading);
To write a file or to create a file that does not exist, you can use the following code:
' In VBScript:
Set Objtstream = objFSO.OpenTextFile ("C:textfilesmyfile.txt", ForWriting, True)

In JScript:
var objtstream = objFSO.OpenTextFile (' C:textfilesmyfile.txt ', ForWriting, true);
If you want to open an existing Unicode file and you are ready to append data to it, but do not create a file that does not exist, you can use:
' In VBScript:
Set Objtstream = objFSO.OpenTextFile ("C:textfilesmyfile.txt", ForReading, _
False, TristateTrue)
In JScript:
var objtstream = objFSO.OpenTextFile (' C:textfilesmyfile.txt ', ForReading, _
Fasle, TristateTrue);
3. Open a File object as a TextStream object
The OpenAsTextStream method of the file object can be used to open the file corresponding to the object, and a TextStream object that can read, write, and append the file is returned. So, given a file object (in this case not a FileSystemObject object)--objfileobject, it can be opened as a "normal" (non-Unicode) TextStream object to append the contents of the file:
' In VBScript:
Set Objtstream = Objfileobject.openastextstream (ForAppending, False)

In JScript:
var objtstream = Objfileobject.opentextfile (ForAppending, false);
Note that you do not need a filename to use this method because the execution of the program is done by referencing the file object, and there is no create argument because the file must already exist, and if you want to start with a new empty file, you can use:
' In VBScript:
Set Objtstream = Objfileobject.openastextstream (ForWriting)

In JScript:
var objtstream = Objfileobject.opentextfile (ForWriting);
If you want to read the file:
' In VBScript:
Set Objtstream = Objfileobject.openastextstream (ForReading)

In JScript:
var objtstream = Objfileobject.opentextfile (ForReading);

5.5.2 TextStream Object Member overview
Table 5-15 and table 5-16 are a list of all the properties and methods of the TextStream object. The details of each of the important members are briefly described below.
1. Properties of the TextStream object
The TextStream property provides information about the current position of the file pointer within the file, as shown in table 5-15. Note that all of the properties are read-only.
Table 5-15 Properties and descriptions of TextStream objects
Property
Description

AtEndOfLine
Returns true if the file position pointer is at the end of a line in the file

AtEndOfStream
Returns true if the file position pointer is at the end of the file

Column
Returns the column number of the current character in the file starting at 1

Line
Returns the line number of the current row in the file starting at 1

The AtEndOfLine and AtEndOfStream properties are available only for files that are opened with the IOMode parameter ForReading, or there will be an error.
2. Methods of TextStream objects
The method for TextStream objects is shown in table 5-16:
The method and description of table 5-16 TextStream object
Method
Description

Close ()
Close an open file

Read (NumChars)
Read NumChars characters from a file

ReadAll ()
Read the entire file as a single string

ReadLine ()
Reads a line from a file as a string (until a carriage return and a newline)

Skip (NumChars)
Ignore NumChars characters when reading from a file

SkipLine ()
Ignore the next line when reading from a file

Write (String)
Write String to File

WriteLine (String)
Writes string (optional) and newline characters to a file

WriteBlankLines (N)
Write n line breaks to a file

3. Write a text file
Once you have used the CreateTextFile, OpenTextFile, or OpenAsTextStream methods, and the ForWriting or forappending parameters, create a TextStream object that corresponds to a file. You can write files and close files using the following VBScript program:
' In VBScript:
Objtstream.writeline "At last I can create files with vbscript!"
Objtstream.writeline
Objtstream.writeline "Here are three blank lines:"
Objtstream.writeblanklines 3
Objtstream.write "... and this is"
Objtstream.writeline "The last line."
Objtstream.close
or use JScript:
In JScript:
Objtstream.writeline (' At the last I can create a files with jscript! ');
Objtstream.writeline ();
Objtstream.writeline (' Here are three blank lines: ');
Objtstream.writeblanklines (3);
Objtstream.write (' ... and is ');
Objtstream.writeline (' The last line. ');
Objtstream.close ();
4. Read a text file
Once you have used the CreateTextFile, OpenTextFile, or OpenAsTextStream methods, and the ForReading parameters, create a TextStream object that corresponds to a file. You can read and close files using the following VBScript program:
' In VBScript:
' Read one line at a time until the ' the ' ' of ' reached
Do as not Objtstream.atendofstream
' Get the line number
Intlinenum = Objtstream.line
' Format it as a 4-character string with leading zeros
Strlinenum = Right ("M" & CStr (Intlinenum), 4)
' Get the ' text of the ' the ' file
Strlinetext = Objtstream.readline
Response.Write Strlinenum & ":" & Strlinetext & "<BR>"
Loop
Objtstream.close
or in JScript:
In JScript:
Read one line at a time until the "end of" the file is reached
while (! Objtstream.atendofstream) {
Get the line number
Intlinenum = Objtstream.line;
Format and convert to a string
Strlinenum = ' + ' + intlinenum.tostring ();
Strlinenum = substr (Strlinenum, Strlinenum.length–4, 4)
Get the text of the line from the file
Strlinetext = Objtstream.readline ();
Response.Write (Strlinenum + ': ' + strlinetext + ' <BR> ');
}
Objtstream.close ();

Examples of 5.5.3 TextStream objects
To understand several ways to manipulate an indelible file using a TextStream object, this book provides a sample VBScript page that uses a lot of the above code. From the CHAPTER05 main Menu page of the example, select the link "Working with the TextStream Object" to open the Show_textstream.asp page.
This page shows the textual content of a file that is stored on disk named MyFile.txt. The text content displayed in the <TEXTAREA> control allows editing, and there are three buttons below. The function of the three buttons is to update (replace) the original text with the contents of the <TEXTAREA> control, add text after the contents of the existing file, or rewrite the file with the original default content, as shown in Figure 5-15:

1. Read the contents of a text file that already exists
Each time the page is loaded, the text file opens and the read content is placed into the <TEXTAREA> control. Notice how we use the Server.MapPath method to get the absolute physical path to the file MyFile.txt, which is in the same directory as the sample page. The following program creates a FileSystemObject instance:
<%
Strtextfile = Server.MapPath ("MyFile.txt")

' Create an instance of a Filesytemobject object
Set objFSO = Server.CreateObject ("Scripting.FileSystemObject")
...
Like most other examples in this section of the book, the page contains a <FORM> section to hold the HTML controls for that page. The action is the current page, so the contents of the form are sent back to the same page.
Each time the page is loaded the,<textarea> control is populated with the current contents of the text file:
...
<form action= "<% = Request.ServerVariables (" Script_name ")%>" method= "POST >

The contents of the disk File <b><% = Strtextfile%></b> are:<p>
<textarea name= "txtcontent" rows= "cols=" wrap= "Physical" >
<%
' Open ' text file as a TextStream object
Set Objtstream = objFSO.OpenTextFile (Strtextfile, ForReading)
' Read one line at a time until the ' the ' ' of ' reached
Do as not Objtstream.atendofstream
' Get the line number
Intlinenum = Objtstream.line
' Format and convert to a string
Strlinenum = Right ("& CStr" (Intlinenum), 3)
' Get the ' text of the ' the ' file
Strlinetext = Objtstream.readline
Response.Write Strlinenum & ":" & Strlinetext & VbCrLf
Loop
Objtstream.close
%>
</TEXTAREA><P>
The above program knows how to open a text file to read, traverse the entire file one line at a time (instead of reading the entire file as a string). This is because you want to add your own line number and the line number does not belong to the text of the file. Retrieves and formats the line attribute and creates a three-digit row number for each line read from the file (before reading). Then place the line number and line of text inside the <TEXTAREA> control of the page.
2. Update the contents of a text file
When you click the Update button on the page (typically after editing the text in the <TEXTAREA> control), the contents of the <TEXTAREA> control are rewritten into the text file. To do this, the page has some corresponding ASP code, check the Request.Form collection before creating the HTML control, see which button is clicked (if any), and then reload the page.
If you click the Update button, collect the contents of the <TEXTAREA> control as a string, detach the string to make it an array of independent text selections, and open the text file to rewrite its contents, and then iterate through the array that you just created, looping through the row number to write the contents of the row:
...
' Look for a command sent ' FORM section buttons
If Len (Request.Form ("Cmdupdate")) Then
' Get contents of TEXTAREA control
strNewText = Request.Form ("Txtcontent")
' Split it into a ' lines at each carriage return
Arrlines = Split (strNewText, vbCrLf)
' Open ' text file for writing, which replaces all existing content
Set Objtstream = objFSO.OpenTextFile (Strtextfile, ForWriting)
For intline = 0 to UBound (arrlines)
Strthisline = Arrlines (intline)
' Write out each line in turn as long as it ' s got a line number
If Len (Strthisline) > 4 Then objtstream.writeline Mid (strthisline, 6)
Next
Objtstream.close
End If
...
The html<textarea> control can add extra characters to the value returned, depending on the content format and the setting of the Wrap property in the original HTML page. In particular, you should write the </TEXTAREA> tag immediately after the ASP script ends with the delimiter "%>" to prevent an additional carriage return symbol from being added. Even with:
%></textarea><p>
Rather than using:
%>
</TEXTAREA><P>
3. Append content to a text file
When you click the Append button, you can append content to an existing file, similar to the contents of the modified file, as shown in Figure 5-16. The difference is that the file is opened for appending, not for overwriting the file. You can add additional parameters when calling the OpenTextFile method to prevent a new file from being created when the specified file 2 does not exist.
...
If Len (Request.Form ("Cmdappend")) Then
' Append contents of TEXTAREA to File
strNewText = Request.Form ("Txtcontent")
Arrlines = Split (strNewText, vbCrLf)
Set Objtstream = objFSO.OpenTextFile (Strtextfile, ForAppending, False)
For intline = 0 to UBound (arrlines)
Strthisline = Arrlines (intline)
If Len (Strthisline) > 4 Then objtstream.writeline Mid (strthisline, 6)
Next
Objtstream.close
End If
...


4. overriding default content
Finally, the Restore button is used to simply rewrite the initial default content back to the text file. The code is similar to writing a text file in a TextStream way:
...
If Len (Request.Form ("Cmddefault")) Then
' Write out default contents to file
Set Objtstream = objFSO.CreateTextFile (Strtextfile, True, False)
Objtstream.writeline "At last I can create files with vbscript!"
Objtstream.writeline
Objtstream.writeline "Here are three blank lines:"
Objtstream.writeblanklines 3
Objtstream.write "... and this is"
Objtstream.writeline "The last line."
Objtstream.close
End If

5.6 Summary
This chapter describes the power of using objects and components in an ASP page. The general characteristics of objects and components, and their types, are discussed first. It then focuses on how to create an object instance within the ASP (and client) scripting code.
Many of the objects used on the page may be "external" components that are installed on the server and are independent of the ASP. The objects discussed in this chapter are always available when an ASP uses a default scripting language, such as VBScript or JScript. The implementation is done through the Script Runtime library in the Scrrun.dll file.
These objects refer to Dictonary objects, FileSystemObject objects, and TextStream objects.
The Dictionary object provides us with an efficient way to store values that can be indexed and accessed by name, rather than by a number. This is the ideal way to store data with name/value pairs.
FileSystemObject objects and TextStream objects are closely related to each other and can use them to access a directory of server or network (mapped) disk drives. The FileSystemObject object provides access to drives, folders (directories), and files, and provides properties and methods for obtaining more information or moving, copying, and deleting them.
You can create a TextStream object that corresponds to any file within the system and read and write the file through that object. It operates as a text file for the read-write process, and can even handle files in Unicode format. The combination of the navigation and read-write capabilities of the file system allows for extremely complex control of the server file system. You can also use objects (with certain restrictions) in client-side scripting code.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.