Java File Operations

Source: Internet
Author: User

This document describes common file operations, including file creation, check, and deletion, Directory Creation, check, and deletion, and obtaining the files and file attributes in the directory, reads and writes file data.

File Path Problems:

Absolute path: e: // Test

In JSP, string Path = request. getrealpath ("");

In Servlet and action, string Path = servlet. getservletcontext (). getrealpath ("");

Folder operation file dirfile = new file (servlet. getservletcontext (). getrealpath ("/test "));

If (! Dirfile. exists ()){

Dirfile. mkdir (); // create a folder

}

If (dirfile. exists ()){

Dirfile. Delete (); // delete a folder

}
* Note: Only empty folders can be deleted. This method cannot delete folders containing files. The solution is to delete all files and directories in the folder first.



Retrieve directory files

String Path = request. getrealpath ("/test ");
File d = new file (PATH); // create the file object of the file in the current directory
File list [] = D. listfiles (); // retrieves an array of file objects representing all files in the directory

For (INT I = 0; I <list. length; I ++ ){

// Files in the directory:
If (List (I). isfile ()){
System. Out .. println (List (I). getname ());
}

// Directory:
If (List (I). isdirectory ()){
System. Out .. println (List (I). getname ());
}
}




Basic File Operations

String Path = servlet. getservletcontext (). getrealpath ("/test ");

File F = new file(path,1.txt );

If (! F. exists ()){

F. createnewfile (); // generate a file

} Else {

F. isfile (); // is a file: Not a file

F. isdirectory (); // is a directory: Not a directory
F. Canread (); // readable: unreadable
F. canwrite (); // writable: not writable
F. ishidden (); // hidden file: Not hidden file
The last modification date of the file is: new date (F. lastmodified ());

F. Delete (); // delete an object

}


Read File data

String Path = request. getrealpath (".");
Filereader Fr = new filereader (path + "// readdata.txt ");
// The key is to determine whether the characters read have reached the end of the file during the reading process,
Whether the character is a broken line character in the file determines whether the character value is 13.
Int c = Fr. Read (); // read a character from the file
// Determine whether the object has been read to the end
While (C! =-1 ){
Out. Print (char) C); // output the read data
C = Fr. Read (); // continue reading data from the file
If (C = 13) {// determines whether the row is a broken line character
Out. Print ("<br>"); // output branch label
Fr. Skip (1); // skip one character
// C = Fr. Read (); // read a character
}
}
Fr. Close ();


Write data to a file

String Path = request. getrealpath (".");
Filewriter fw = new filewriter (path + "// writedata.txt"); // create a filewriter object and instantiate the FW

Bufferedwriter BW = new bufferedwriter (FW );
// Write a string to a file
Bw. Write ("test! ");

Bw. newline (); // disconnected
Bw. Write ("write data to a text file! ");

Bw. Flush (); // update data to a file
FW. Close ();


How to append data to a file

String Path = request. getrealpath (".");
Randomaccessfile Rf = new randomaccessfile (path + "// writedata.txt", "RW ");
// Define an object of the randomaccessfile class and instantiate it.
RF. Seek (RF. Length (); // move the pointer to the end of the file
RF. writebytes ("/nappend a line to the file! ");
RF. Close (); // close the file stream




// Get the filename extension

Public static string getfilesuffix (string filename ){

String suffixname = NULL;

If (filename! = NULL & filename. indexof (".")! =-1 ){

Suffixname = filename. substring (filename. indexof ("."));

} Else {

Return "invalid file ";

}

Return suffixname;

}


The Java. Io. File class completes the naming of folder management, queries file attributes, and processes directories. It does not read folder content. The following describes the main common methods of the file class.
File (): constructor, which generally creates a file object based on the specified location of the file.
Canwrite (): whether the returned file is writable.
Canread (): whether the returned object is readable.
Compareto (File pathname): checks the order between the specified file paths.
Createnewfile (): An empty file is generated when the file does not exist.
Delet (): delete the file from the file system.
Deleteonexit (): delete files from the system when the program ends successfully.
Equals (Object OBJ): checks whether the path name of a specific object is equal.
Exists (): determines whether a folder exists.
Getabsolutefile (): The complete path of the returned file.
Getabsolutepath (): The complete path of the returned file.
Getname (): name of the returned object. Getparent (): returns the path of the parent directory of the file.
Getpath (): potential relative path of the returned file.
Getparentfile (): return the path of the folder where the file is located.
Hashcode (): returns the file hash code.
Isdirectory (): determines whether the PATH represents a directory.
Isfile (): determines whether the path indicates a file.
Lastmodified (): The last modification time mark of the returned object.
Length (): the length of the returned file.
List (): List of returned files and directories.
Mkdir (): generate the specified directory.
Renameto (File DEST): Rename the file.
Setreadonly (): Set the file to read-only.
Tostring (): string that returns the File status.
Tourl (): Convert the file path string to a URL.



-- From: http://hi.baidu.com/huaiyu2008/blog/item/acd769185360b5b14aedbc8b.html

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.