Java local file operations

Source: Internet
Author: User

Java local file operations
1. Introduction to the File class

All transactions in java are objects and files are no exception. in java, the File class is used to represent files (including files and folders ).

Ii. Create, delete, and rename a file 2.1

First, create a File object f1, input the string parameter as the File name, and then use the createNewFile () method to create the File. The createNewFile () method returns true, if creation fails, false is returned. if the file already exists, creation will fail. You can use the exists () method to check whether the file exists.

Package ucas. file. test; import java. io. file; import java. io. IOException; public class FileDemo01 {public static void main (String [] args) {File f1 = new File ("Test.txt"); try {if (f1.exists () {System. out. println ("file already exists. You do not need to create it! ");} Else {if (f1.createNewFile () {System. out. println (" File Created successfully! ");} Else {System. out. println (" file creation failed! ") ;}} Catch (IOException e) {e. printStackTrace ();}}}
2.2 Delete a file

Delete an object using the delete () method.

Package ucas. file. test; import java. io. file; public class FileDeete {public static void main (String [] args) {File f1 = new File ("Test.txt"); if (f1.exists () = false) {System. out. println ("the file does not exist. deletion failed! ");} Else {if (f1.delete () {System. out. println (" deleted successfully! ") ;}Else {System. out. println (" failed to delete ");}}}}
2.3 rename a file

There is a test.txt text file in the srcdirectory. Modify the file name:

package ucas.file.test;import java.io.File;public class FileRename {    public static void main(String[] args) {         File f1=new File("src/Test.txt");         File f2=new File("src/TestTwo.txt");         f1.renameTo(f2);    }}
3. Create, delete, and rename folders 3.1

Create a folder using the mkdir () method:

package ucas.file.test;import java.io.File;public class FileFolder {    public static void main(String[] args) {          File dir1=new File("src/Folder");          dir1.mkdir();        }}

In this way, a new Folder is created under the src directory, which is visible after being refreshed.
When creating a folder, first determine whether the folder exists. This is more standard:

Package ucas. file. test; import java. io. file; public class FileFolder {public static void main (String [] args) {File dir1 = new File ("src/Folder"); if (dir1.exists () {System. out. println ("the folder already exists! ");} Else {if (dir1.mkdir () {System. out. println ("folder created successfully");} else {System. out. println ("failed to create folder ");}}}}
3.2 Create multi-level folders

Use the mkdirs () function to create a folder in the sub-Folder:

File dir1=new File("Folder/one/two");dir1.mkdirs()
3.3 delete a folder

The delete () function is used to delete folders. However, non-empty folders cannot be deleted at one time.
To delete a non-empty folder, you can use recursion:

public static void deleteFolder(File dir) {        File dirFile[] = dir.listFiles();        for (int i = 0; i < dirFile.length; i++) {            if (dirFile[i].isDirectory()) {                deleteFolder(dirFile[i]);            }            dirFile[i].delete();        }    }
Iv. Reading file attributes
Package ucas. file. demo; import java. io. file; public class FileDemo3 {public static void main (String [] args) {// Read File file File = new File ("text.txt") for File attributes "); // determine whether the file exists in System. out. println ("determine whether a file exists:" + file. exists (); // read the file name System. out. println ("Read file Name:" + file. getName (); // read the file path System. out. println ("Read file Path:" + file. getPath (); // read the absolute file path System. out. println ("absolute path to read files:" + file. getAbsolutePath (); // read the file parent path System. out. println ("parent File path:" + new file (File. getAbsolutePath ()). getParent (); // read the file size System. out. println ("file size:" + (float) file. length ()/1000 + "Kb"); // whether the file is hidden System. out. println ("Whether the file is hidden:" + file. isHidden (); // whether the file is readable System. out. println ("file readable:" + file. canRead (); // whether the file can be written to System. out. println ("file writable:" + file. canWrite (); // determines whether the folder is System. out. println ("determine whether it is a folder:" + file. isDirectory ());}}
V. File attribute settings

File readable, writable, and read-only settings:

// Set the file attribute to writable: file. setWritable (true); // set the file attribute to readable: file. setReadable (true); // set file Read-Only: file. setReadOnly ();
6. Traverse folders
Package ucas. file. demo; import java. io. file; public class FileDemo5 {public static void main (String [] args) {// traverse folders // File dir = new File ("/Users/yaopan/Documents "); file dir = new File (".. /"); printFiles (dir, 1);} public static void printFiles (File dir, int tab) {if (dir. isDirectory () {File next [] = dir. listFiles (); for (int I = 0; I <next. length; I ++) {for (int j = 0; j
  

Output result:

| --. Classpath | --. DS_Store | --. project | --. settings | -- org. eclipse. jdt. core. prefs | -- bin | --. DS_Store | -- Folder | -- one | -- two | -- | --TestTwo.txt | -- ucas | -- collection | -- | -- demo | -- HashSetDemo. class | -- IteratorDemo. class | -- ListDemo. class | -- MapDemo01.class | -- SetDemo. class | -- VectorDemo. class | -- file | -- demo | -- FileDemo1.class | -- FileDemo2.class | -- | -- FileDemo3.class | -- FileDemo4.class | -- FileDemo5.class | -- | -- FileDemo6.class | -- test | -- FileDeete. class | -- FileDemo01.class | -- FileFolder. class | -- FileRename. class | -- xml | -- demo | -- XmlDemo1.class | -- My Folder | -- two | -- | -- | -- three | -- src | --. DS_Store | -- Folder | -- | --1.txt | -- 1 copy 2.txt | -- 1 copy 3.txt | -- 1 copy 4.txt | -- | -- 1 copy 5.txt | -- 1 copy 6.txt | -- 1 copy 7.txt | -- 1 copy 8.txt | -- | -- 1 copy 9.txt | -- | --1subscript .txt | -- one | -- | --TestTwo.txt | -- ucas | -- collection | -- | -- demo | -- HashSetDemo. java | -- IteratorDemo. java | -- ListDemo. java | -- MapDemo01.java | -- SetDemo. java | -- VectorDemo. java | -- file | -- demo | -- FileDemo1.java | -- FileDemo2.java | -- | -- FileDemo3.java | -- FileDemo4.java | -- FileDemo5.java | -- | -- FileDemo6.java | -- test | -- FileDeete. java | -- FileDemo01.java | -- FileFolder. java | -- FileRename. java | -- xml | -- demo | -- XmlDemo1.java | --tangshi.txt | --tangshi2.txt | --Test.txt | --text.txt
VII. Simple file read/write

Put a tangshi.txt in the project directory, which inputs text, reads output and writes:

Package ucas. file. demo; import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStreamWriter; import java. io. unsupportedEncodingException; public class FileDemo6 {public s Tatic void main (String [] args) {// File for simple Reading and Writing file File = new file ("tangshi.txt"); try {FileInputStream FD = new FileInputStream (File ); inputStreamReader isr = new InputStreamReader (FCM, "UTF-8"); BufferedReader bfr = new BufferedReader (isr); String line; while (line = bfr. readLine ())! = Null) {System. out. println (line);} bfr. close (); isr. close (); FCM. close ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (UnsupportedEncodingException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} File file2 = new File ("tangshi2.txt"); try {FileOutputStream fos = new FileOutputStream (file2); OutputStreamWriter osq = new OutputStreamWriter (fos); Buf FeredWriter bfw = new BufferedWriter (osq); bfw. write ("boarding sparrow building \ n"); bfw. write ("Tang Wang Zhizhi \ n"); bfw. write ("the Yellow River enters the current when the sun goes down. \ N "); bfw. write (" the Yellow River enters the current when the sun falls to the mountains. \ N "); bfw. close (); osq. close (); fos. close (); System. out. println (" write complete! ");} Catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}

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.