Javascript-file operations [personal favorites]

Source: Internet
Author: User
I. function implementation core: FileSystemObject object
To implement file operations in Javascript, FileSystemObject objects are primarily used.
Ii. FileSystemObject Programming
It is very easy to program with FileSystemObject object. Generally, the following steps are required: Create a FileSystemObject object, apply related methods, and access object attributes.
(1) create a FileSystemObject object
Only one line of code is required to create a FileSystemObject object:
VaR FSO = new activexobject ("scripting. FileSystemObject ");
After the above code is executed, FSO becomes a FileSystemObject object instance.
(2) Application-related methods
After creating an object instance, you can use the object-related methods. For example, use the createtextfile method to create a text file:
VaR FSO = new activexobject ("scripting. FileSystemObject ");
VaR F1 = FSO. createtextfile ("C: // myjstest.txt", true ");
(3) Access Object Attributes
To access the relevant properties of an object, you must first create a handle pointing to the object, which must be implemented through the get series method: getdrive is responsible for obtaining the drive information, getfolder is responsible for obtaining the folder information, getFile obtains the file information. For example, after pointing to the following code, F1 becomes the handle pointing to the file C: // test.txt:
VaR FSO = new activexobject ("scripting. FileSystemObject ");
VaR F1 = FSO. GetFile ("C: // myjstest.txt ");
Then, use F1 to access the relevant attributes of the object. For example:
VaR FSO = new activexobject ("scripting. FileSystemObject ");
VaR F1 = FSO. GetFile ("C: // myjstest.txt ");
Alert ("file last modified:" + f1.datelastmodified );
After the last sentence is executed, the Last modified Date attribute value of C: // myjstest.txt is displayed.
Note: For objects created using the create method, you do not need to use the get method to obtain the object handle. In this case, you can directly use the name of the handle created using the create method:
VaR FSO = new activexobject ("scripting. FileSystemObject ");
VaR F1 = FSO. createtextfile ("C: // myjstest.txt", true ");
Alert ("file last modified:" + f1.datelastmodified );
3. Drive)
It is easy to use FileSystemObject objects to program drive and folder operations, just like performing interactive operations on files in a Windows file browser, such as copying and moving folders, obtain the attributes of a folder.
(1) drives Object Attributes
The drive object collects the content of physical or logical drive resources in the system. It has the following attributes:
L totalsize: the size of the drive in bytes.
L availablespace or freespace: The drive space in bytes.
L driveletter: drive letter.
L drivetype: Drive Type, value: Removable (Mobile Medium), fixed (fixed medium), Network (Network Resources), CD-ROM or ramdisk.
L serialnumber: the serial number of the drive.
L filesystem: The file system type of the drive. Values: fat, FAT32, and NTFS.
L isready: whether the drive is available.
L sharename: Share Name.
L volumename: the name of the volume label.
L path and rootfolder: The drive path or root directory name.
(2) Drive object operation routine
The following routine displays the volume label, total capacity, and available space of drive C:
VaR FSO, DRV, S = "";
FSO = new activexobject ("scripting. FileSystemObject ");
DRV = FSO. getdrive (FSO. getdrivename ("C :////"));
S + = "drive C:" + "-";
S + = DRV. volumename + "// n ";
S + = "total space:" + DRV. totalsize/1024;
S + = "kb" + "// n ";
S + = "Free Space:" + DRV. freespace/1024;
S + = "kb" + "// n ";
Alert (s );
4. Folders)
Folder operations include creating, moving, deleting, and obtaining related properties.
Folder object operation routine:
The following routine obtains the parent folder name, creates a folder, deletes a folder, and determines whether the folder is the root directory:
VaR FSO, FLDR, S = "";
// Create a FileSystemObject object instance
FSO = new activexobject ("scripting. FileSystemObject ");
// Get the drive object
FLDR = FSO. getfolder ("C :////");
// Display the parent directory name
Alert ("parent folder name is:" + FLDR + "// n ");
// Display the drive name
Alert ("contained on drive" + FLDR. Drive + "// n ");
// Determine whether the root directory is used
If (FLDR. isrootfolder)
Alert ("this is the root folder .");
Else
Alert ("this folder isn/'t a root folder .");
Alert ("// N // n ");
// Create a new folder
FSO. createfolder ("C: // bogus ");
Alert ("created folder C: // bogus" + "// n ");
// Display the basic folder name, excluding the path name
Alert ("basename =" + FSO. getbasename ("C: // bogus") + "// n ");
// Delete the created folder
FSO. deletefolder ("C: // bogus ");
Alert ("deleted folder C: // bogus" + "// n ");
5. Files)
The operations on files are more complex than the drive and folder operations described above. They are basically divided into the following two categories: create, copy, move, and delete objects, and create, add, delete, and read objects. The following describes in detail.
(1) create a file
There are three methods to create an empty text file, which is also called a text stream ).
The first method is to use the createtextfile method. The Code is as follows:
VaR FSO, F1;
FSO = new activexobject ("scripting. FileSystemObject ");
F1 = FSO. createtextfile ("C: // testfile.txt", true );
The second method is to use the opentextfile method and add the forwriting attribute. The value of forwriting is 2. The Code is as follows:
VaR FSO, TS;
VaR forwriting = 2;
FSO = new activexobject ("scripting. FileSystemObject ");
TS = FSO. opentextfile ("C: // test.txt", forwriting, true );
The third method is to use the openastextstream method and set the forwriting attribute. The Code is as follows:
VaR FSO, F1, TS;
VaR forwriting = 2;
FSO = new activexobject ("scripting. FileSystemObject ");
FSO. createtextfile ("C: // test1.txt ");
F1 = FSO. GetFile ("C: // test1.txt ");
TS = f1.openastextstream (forwriting, true );
(2) Add data to a file
After a file is created, you can add data to the file by following the steps of "Open File> Fill in data> close file.
To open a file, you can use the opentextfile method of the FileSystemObject object or the openastextstream method of the file object.
Use the write, writeline, or writeblanklines methods of the textstream object to fill in the data. With the same function of writing data, the difference between the three is that the write method does not add a new line break at the end of the written data, and the writeline method must add a new line break at the end, writeblanklines adds one or more empty lines.
To close a file, use the close method of the textstream object.
(3) create a file and add a data routine
The following code combines the steps of creating a file, adding data, and closing a file for application:
VaR FSO, TF;
FSO = new activexobject ("scripting. FileSystemObject ");
// Create a new file
TF = FSO. createtextfile ("C: // testfile.txt", true );
// Fill in the data and add a line break
TF. writeline ("Testing 1, 2, 3 .");
// Add 3 empty rows
TF. writeblanklines (3 );
// Enter a line without a line break
TF. Write ("this is a test .");
// Close the file
TF. Close ();
(4) Reading File Content
To read data from a text file, use the read, Readline, or readall methods of the textstream object. The read method is used to read a specified number of characters in a file. The Readline method reads a whole line, but does not include line breaks. The readall method reads the entire content of a text file. The read content is stored in string variables for display and analysis. When reading the file content using the read or Readline method, if you want to skip some parts, you need to use the skip or skipline method.
The following code demonstrates opening a file, entering data, and then reading data:
VaR FSO, F1, ts, S;
VaR forreading = 1;
FSO = new activexobject ("scripting. FileSystemObject ");
// Create a file
F1 = FSO. createtextfile ("C: // testfile.txt", true );
// Enter a data row
F1.writeline ("Hello World ");
F1.writeblanklines (1 );
// Close the file
F1.close ();
// Open the file
TS = FSO. opentextfile ("C: // testfile.txt", forreading );
// Read a row of content from the file to a string
S = ts. Readline ();
// Display string Information
Alert ("File Contents =/'" + S + "/'");
// Close the file
TS. Close ();
(5) moving, copying, and deleting objects
For the above three file operations, JavaScript has two corresponding methods: file. move or FileSystemObject. movefile is used to move files. File. copy or FileSystemObject. copyfile is used to copy files. File. delete or FileSystemObject. deletefile is used to delete objects.
The following code creates a text file under the root directory of drive C, fills in some content, and then moves the file to the // tmp directory, create a file copy under the directory // temp and delete the files in these two directories:
VaR FSO, F1, F2, S;
FSO = new activexobject ("scripting. FileSystemObject ");
F1 = FSO. createtextfile ("C: // testfile.txt", true );
// Write a row
F1.write ("this is a test .");
// Close the file
F1.close ();
// Obtain the file handle in the C: // root directory
F2 = FSO. GetFile ("C: // testfile.txt ");
// Move the file to the // tmp directory
F2.move ("C: ///tmp // testfile.txt ");
// Copy the file to the // temp directory
F2.copy ("C: // temp // testfile.txt ");
// Obtain the file handle
F2 = FSO. GetFile ("C: // TMP // testfile.txt ");
F3 = FSO. GetFile ("C: // temp // testfile.txt ");
// Delete an object
F2.delete ();
F3.delete ();
Vi. Closed speech
Through the introduction and examples of FileSystemObject's various objects, attributes, and methods, I believe you have a clear understanding of how to use JavaScript to operate drives, files, and folders on pages. However, the routines mentioned above are very simple. To fully and flexibly master the Javascript file operation technology, a lot of practical exercises are required. In addition, we would like to remind you that, due to advanced operations such as file reading and writing in the browser, there will be a message before the code is run for the default browser security level, note this in the actual environment.
<

Posted on wise man Wuji reading (30) Comments (4) EDIT add to favorites reference favorites to 365key category: about Ajax

Comment:

  • # Re: javascript-a wise man in file operations without Borders posted @

    Use JavaScript to read and write XML files
    Take student information as an example.
    3 files are used: studentinfo.html, studentinfo. XML, and studentinfonew. xml.

    Studentinfo. xml --- Student Information
    <? XML version = "1.0"?>
    <Studentlist>
    <Student>
    <ID> 213 </ID>
    <Name> ASD </Name>
    <Age> SDF </age>
    </Student>
    <Student>
    <ID> rfwer </ID>
    <Name> </Name>
    <Age> </age>
    </Student> </studentlist>

    Studentinfonew. xml --- newly added blank Student Information Template
    <? XML version = "1.0" encoding = "gb2312"?>
    <Studentlist>
    <Student>
    <ID> </ID>
    <Name> </Name>
    <Age> </age>
    </Student>
    </Studentlist>

    Studentinfo.html --- added, deleted, and modified User UI
    <HTML> <body bgcolor = # a1bae6>
    <XML id = xmldso src = "studentinfo. xml"> </XML>
    <XML id = studentinfonew> </XML> <! -- Jia? XML data -->
    <Script language = JavaScript>
    Studentinfonew. async = false;
    Studentinfonew. Load ("studentinfonew. xml ");

    Function display (){
    VaR Doc = xmldso. xmldocument;
    Alert (Doc. XML );
    }

    Function save (){
    Try {
    VaR Doc = xmldso. xmldocument;
    Alert (Doc. XML );
    VaR strfile = "";
    VaR FSO, F, TS;
    VaR S = "E: // zookeeper // XML // javascript_readwritexml // studentinfo. xml ";
    VaR forreading = 1, forwriting = 2, forappending = 8;
    VaR tristateusedefault =-2, tristatetrue =-1, tristatefalse = 0;
    FSO = new activexobject ("scripting. FileSystemObject ");
    If (! FSO. fileexists (s )){
    Alert (S + "is not exist! ");
    } Else {
    F = FSO. GetFile (s );
    TS = f. openastextstream (forwriting, tristateusedefault );
    TS. writeline (Doc. XML );
    TS. Close ();
    }
    } Catch (e ){
    Alert (E );
    }

    }

    // Add ??;
    Function addid (){
    VaR Doc = xmldso. xmldocument;
    VaR rootnode‑doc.doc umentelement;
    VaR sortnode = rootnode. selectnodes ("// ID ");
    VaR currentid = sortnode. Length-1;
    VaR cc = "";
    If (currentid =-1 ){
    VaR node = studentinfonedomaindoc umentelement. childnodes (0). clonenode (true );
    Xmldso.doc umentelement. appendchild (node );
    } Else {
    Cc = sortnode. Item (currentid). text;
    If (Cc = "AA") | (Cc = "")){
    Alert ("? After entering the last row of data? And then add a new ??! ");
    } Else {
    VaR node = studentinfonedomaindoc umentelement. childnodes (0). clonenode (true );
    Xmldso.doc umentelement. appendchild (node );
    }
    }
    }
    //? Except ??
    Function delid (whichtasks ){
    VaR Doc = xmldso. xmldocument;
    VaR rootnode‑doc.doc umentelement;
    VaR sortnode = rootnode. selectnodes ("// student ");
    If (sortnode. Length = 1 ){
    Alert ("can not do Delete when there is only 1 record ");
    Return;
    }

    VaR sortnode = xmldso. selectsinglenode ("// student/ID [text () = '" + which.pdf + "']");
    Try {
    Sortnode. parentnode. parentnode. removechild (sortnode. parentnode );
    } Catch (e ){
    }
    }
    </SCRIPT>

    <Center> <B> Student-studentlist </B> <br>
    <Table id = "table" datasrc = '# xmldso' border cellpadding = 3>
    <! --? Row data? Set -->
    <Thead> <TH> id </Th> <TH> name </Th> <TH> age </Th> </thead>
    <Tr>
    <TD> <acronym Title = 'Point? OK? Except ??? '> <Input type = button size = 4 dataworks = "ID" onclick = "delid (this. Value)"> </acronym> </TD>
    <TD> <input type = text dataworks = "ID"> </TD>
    <TD> <input type = text dataworks = "name"> </TD>
    <TD> <input type = text dataworks = "Age"> </TD>
    </Tr>
    </Table>
    <Input type = button name = dd id = DD value = "add" onclick = "addid ();">
    <Input type = button name = Cc id = Cc value = "save" onclick = "Save ()">
    <Input type = button name = EE id = ee value = "display" onclick = "Display ()"> </center> </body>

    Reply

  • # Re: javascript-file operation self posted @

    When JavaScript cannot create file objects, you can run regsvr32 scrrun. dll in the running state to enable this program,
    If not, set the intermediate level in the security level of IE. Reply

  • # Re: javascript-file operation self posted @ 2006-12-01 16:16:06

    Below is a JS File Read and Write Program I wrote:
    1. <! -- & Copy; zhanglijun 2006-12-1
    Task: create a file in JS, write data, and read data
    Add, modify, and delete data.
    -->
    <HTML>
    <Head>
    <Title> jsio </title>
    </Head>
    <SCRIPT type = "text/JavaScript" src = "fileio. js"> </SCRIPT>
    <Body> <p align = "center">
    Specified folder: <input type = "text" id = "path"/> <br>
    File Name:
    <Input type = text id = "name"/> <br>
    File Content:
    <Textarea id = "content" width = 20px Height = 35px> </textarea> <br>
    <Input type = button value = "CREATE" onclick = "Return createfile ();"/>
    <Input type = button value = "read data" onclick = "Return readfile ();"/>
    <Br>
    Run regsvr32 scrrun. dll in the running state. <br>
    Then, in IE's security --> Custom Level --> Reset to --> select intermediate
    </P>
    </Body>
    2 fileio. js
    /*
    * Js file read/write module by zhanglijun 2006-12-1
    */

    Function createfile (){
    If (check () = false) return false;
    VaR name = Document. getelementbyid ("name"). value;
    VaR name1 = Name. Split (".");
    If (name1 [1] = undefined) name = Name + ". txt ";
    // Alert (name );
    Pathandname = Document. getelementbyid ("path"). Value + name;
    // Alert (pathandname );
    VaR FSO = new activexobject ("scripting. FileSystemObject ");
    VaR F1 = FSO. createtextfile (pathandname );
    If (! F1) Alert ("file creation failed ");
    Else alert ("the file is successfully created, and content is written below ");
    F1.write (document. getelementbyid ("content"). value );
    If (f1.read ()! = "") Alert ("the content has been written ");
    F1.close ();
    }

    Function readfile (){
    If (checkread () = false) return false;
    VaR name = Document. getelementbyid ("name"). value;
    VaR name1 = Name. Split (".");
    If (name1 [1] = undefined) name = Name + ". txt ";
    // Alert (name1 [1]);
    Pathandname = Document. getelementbyid ("path"). Value + name;
    // Alert (pathandname );
    VaR FSO = new activexobject ("scripting. FileSystemObject ");
    VaR F2
    Try {
    F2 = FSO. opentextfile (pathandname );
    } Catch (e) {alert (name + "not found ");}
    VaR A = "";
    While (! F2.atendofstream ){
    A + = f2.readline ();}
    F2.close ();
    Content. innerhtml =;
    Alert ("its location is" + pathandname );
    }
    Function check (){
    If (document. getelementbyid ("name"). value = "" | document. getelementbyid ("content"). value = "")
    {Alert ("the file name and content cannot be blank! ");
    Document. getelementbyid ("name"). Focus (); Return false ;}

    } Function checkread (){
    If (document. getelementbyid ("name"). value = "")
    {Alert ("the file name and content cannot be blank! ");
    Document. getelementbyid ("name"). Focus (); Return false ;}

    }
    Function changesrc (filepicker)
    {
    Ofilechecker. src = filepicker. value;
    }
    </Html> reply

  • # Re: javascript-file operation self posted @ 2006-12-01 16:16: 40

    Use js fso object to write XML files
    <HTML> <Title> opratexml </title>
    </Head>
    <SCRIPT type = "text/JavaScript">
    <! --
    Function createxml (){

    VaR FSO, tempfolder, xmlfile, schar;
    FSO = new activexobject ("scripting. FileSystemObject ");
    Xmlfile = FSO. createtextfile ("C: // test2.xml", true, true );
    Schar = '/R ';
    Xmlfile. writeline ('<? XML version = "1.0" encoding = "UTF-16"?> '+ Schar );
    Xmlfile. writeline ('<document title = "information">' + schar );
    For (VAR I = 0; I <10; I ++ ){
    Xmlfile. writeline ('<xmlnode type = "Node" name = "node' + I +'"/> '+ schar );
    }
    Xmlfile. writeline ('</document> ');
    Xmlfile. Close ();
    }
    --> </SCRIPT>
    <Body>
    <Input type = "button" value = "write XML file" onclick = "createxml ()"/>
    </Body>
    </Html>
    The result is as follows:
    <? XML version = "1.0" encoding = "UTF-16"?>
    -<Document title = "information">
    <Xmlnode type = "Node" name = "node0"/>
    <Xmlnode type = "Node" name = "node1"/>
    <Xmlnode type = "Node" name = "node2"/>
    <Xmlnode type = "Node" name = "node3"/>
    <Xmlnode type = "Node" name = "node4"/>
    <Xmlnode type = "Node" name = "node5"/>
    <Xmlnode type = "Node" name = "node6"/>
    <Xmlnode type = "Node" name = "node7"/>
    <Xmlnode type = "Node" name = "node8"/>
    <Xmlnode type = "Node" name = "node9"/>
    </Document>

  • Reprinted thanks: http://www.blogjava.net/zhanglijun33/
Related Article

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.