Home >Web Front-end >JS Tutorial >Javascript----File operation_javascript skills

Javascript----File operation_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:20:46889browse

Javascript----File Operation
1. Functional Implementation Core: FileSystemObject Object
To implement the file operation function in JavaScript, we mainly rely on the FileSystemobject object.
2. FileSystemObject Programming
Programming using the FileSystemObject object is very simple. Generally, you need to go through the following steps: Create a FileSystemObject object, apply related methods, and access object-related properties.
(1) Create a FileSystemObject object
The code to create a FileSystemObject object only needs one line:
var fso = new ActiveXObject("Scripting.FileSystemObject");
After the above code is executed, fso becomes a FileSystemObject Object instance.
(2) Apply related methods
After creating an object instance, you can use the related methods of the object. 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) Accessing object-related attributes
To access object-related attributes, you must first establish a handle to the object, which is achieved through the get series of methods: GetDrive is responsible for obtaining drive information, GetFolder is responsible for obtaining folder information, GetFile Responsible for obtaining 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 related properties 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 executing the last sentence above, the last modified date attribute of c:myjstest.txt will be displayed Value.
But please note one thing: for objects created using the create method, you no longer need to use the get method to obtain the object handle. In this case, you can directly use the handle name created by the create method:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f1 = fso.createtextfile("c:\myjstest.txt",true");
alert("File last modified: " f1.DateLastModified);
3. Operating drives (Drives)
It is easy to use FileSystemObject objects to programmatically operate drives (Drives) and folders (Folders), just like interacting with files in the Windows file browser, such as: copy, Move a folder and get the properties of the folder.
(1) Drives object attributes
The Drive object is responsible for collecting the physical or logical drive resource content in the system. It has the following attributes:
l TotalSize: The drive size calculated in bytes.
l AvailableSpace or FreeSpace: The available space of the drive calculated in bytes.
l DriveLetter: drive letter.
l DriveType: Drive type, the value is: removable (removable media), fixed (fixed media), network (network resource), CD-ROM or RAM disk.
l SerialNumber: The serial number of the drive.
l FileSystem: The file system type of the drive, the values ​​are FAT, FAT32 and NTFS.
l IsReady: Whether the drive is available.
l ShareName: Share name.
l VolumeName: Volume name.
l Path and RootFolder: The path or root directory name of the drive.
(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. Operation folders (Folders)
Operations involving folders include creation, movement, deletion and acquisition Related properties.
Folder object operation routine:
The following routine will practice operations such as obtaining the name of the parent folder, creating a folder, deleting a folder, and determining whether it is the root directory:
var fso, fldr, s = "";
// Create FileSystemObject object instance
fso = new ActiveXObject("Scripting.FileSystemObject");
// Get Drive object
fldr = fso.GetFolder("c:\") ;
// Display the name of the parent directory
alert("Parent folder name is: " fldr "n");
// Display the name of the drive
alert("Contained on drive " fldr.Drive "n");
// Determine whether it is the root directory
if (fldr.IsRootFolder)
alert("This is the root folder.");
else
alert("This folder isn't a root folder.");
alert("nn");
// Create a new folder
fso.CreateFolder ("C:\Bogus");
alert( "Created folder C:\Bogus" "n");
// Display the folder base 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 , operating files (Files)
The operations on files are more complicated than the drive (Drive) and folder (Folder) operations introduced above. They are basically divided into the following two categories: creating, copying, and moving files. , deletion operations and creation, addition, deletion and reading operations on file content. Each is introduced in detail below.
(1) Create a file
There are 3 methods to create an empty text file, which is sometimes called a text stream.
The first 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 also 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 the file
When After the file is created, you generally need to follow the steps of "open file -> fill in data -> close file" to add data to the file.
To open a file, you can use the OpenTextFile method of the FileSystemObject object, or the OpenAsTextStream method of the File object.
To fill in data, use the Write, WriteLine or WriteBlankLines method of the TextStream object. Under the same function of writing data, the difference between these three methods is that the Write method does not add a new line break at the end of the written data, the WriteLine method adds a new line break at the end, and WriteBlankLines adds one or more blanks. OK.
To close the file, you can use the Close method of the TextStream object.
(3) Routines for creating files and adding data
The following code combines the steps of creating files, adding data, and closing files:
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 newline character
tf.WriteLine("Testing 1, 2, 3.") ;
// Add 3 blank lines
tf.WriteBlankLines(3) ;
// Fill in one line without newlines
tf.Write ("This is a test.");
//Close the file
tf.Close();
(4) Read the file content
Read from the text file To get data, use the Read, ReadLine or ReadAll method of the TextStream object. The Read method is used to read a specified number of characters in the file; the ReadLine method reads an entire line, excluding newlines; and the ReadAll method reads the entire content of the text file. The read content is stored in a string variable for display and analysis. When using the Read or ReadLine method to read the file content, if you want to skip some parts, you must use the Skip or SkipLine method.
다음 코드는 파일을 열고 데이터를 채운 다음 데이터를 읽는 방법을 보여줍니다.
var fso, f1, ts, s
var ForReading = 1
fso = new ActiveXObject( "Scripting.FileSystemObject ");
// 파일 생성
f1 = fso.CreateTextFile("c:\testfile.txt", true)
// 데이터 한 줄 채우기
f1.WriteLine("Hello World" );
f1.WriteBlankLines(1);
// 파일 닫기
f1.Close()
// 파일 열기
ts = fso.OpenTextFile("c:\testfile.txt", ForReading);
// 파일 내용을 문자열로 읽습니다.
s = ts.ReadLine()
// 문자열 정보 표시
alert("파일 내용 = '" s "'");
//파일 닫기
ts.Close()
(5) 파일 이동, 복사 및 삭제
위의 세 가지 파일 작업에는 두 가지 해당 메서드가 있습니다. File.Move 또는 FileSystemObject.MoveFile은 파일을 이동하는 데 사용되며 File.Delete 또는 FileSystemObject.DeleteFile은 파일을 삭제하는 데 사용됩니다. 파일.
다음 코드는 C 드라이브의 루트 디렉터리에 텍스트 파일을 만들고 일부 내용을 채운 다음 파일을 tmp 디렉터리로 이동하고 temp 디렉터리 아래에 파일 복사본을 만들고 마지막으로 파일을 삭제하는 방법을 보여줍니다. :
var fso, f1, f2, s;
fso = new ActiveXObject("Scripting.FileSystemObject")
f1 = fso.CreateTextFile("c:\testfile.txt", true);
// 한 줄 작성
f1.Write("테스트입니다.")
// 파일 닫기
f1.Close()// Get C: 루트 디렉터리 파일 핸들
f2 = fso.GetFile("c:\testfile.txt")
// 파일을 mp 디렉터리로 이동합니다.
f2.Move("c:\tmp \testfile.txt") ;
//emp 디렉터리에 파일을 복사합니다
f2.Copy ("c:\temp\testfile.txt");
// 파일 핸들 가져오기
f2 = fso.GetFile("c :\tmp\testfile.txt");
f3 = fso.GetFile("c:\temp\testfile.txt")
// 파일 삭제
f2 .Delete();
f3.Delete();
6. 결론
위의 소개와 FileSystemObject의 다양한 객체, 속성 및 메소드의 예를 통해 여러분은 이미 JavaScript 언어를 사용하는 방법을 알고 계실 것입니다. 페이지의 드라이브, 파일 및 파일을 작동하는 방법을 명확하게 이해했습니다. 그러나 위에서 언급한 루틴은 매우 간단하며 JavaScript 파일 조작 기술을 완전하고 유연하게 익히려면 많은 실습이 필요합니다. 그리고 한 가지 더 알려드릴 점은, 브라우저에서 파일을 읽고 쓰는 등의 고급 작업이 포함되기 때문에 기본 브라우저 보안 수준의 경우 코드가 실행되기 전에 정보 프롬프트가 표시된다는 점입니다. 실제 환경에서 이를 확인하세요. 방문자에게 주의를 기울이도록 유도합니다.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn