Java Learning (eight): Java file programming

Source: Internet
Author: User

This blog post mainly introduces Java file programming, mainly including the I/O from the JDK to read and write data from the file, byte stream read and write files, the way the character stream read and write files, how to use the file class to create, delete and traverse files and directories and other operations.


Whether it is a C + + or Java, it is possible to generate some persistent data, we can store the data in a file or database, but for some simple data, if stored in the database, it will be a little more than the loss, then, How to store data in a file in Java becomes a basic skill that small and medium-sized programs must master.


The following one by one explains the file class introduction and the creation, deletion, renaming, folder creation, renaming, deletion, file attributes reading, file property settings, traverse folder, file simple Read and write, and all show example code.


1. Introduction of File class and creation, deletion and renaming of files


The main content includes the file class, which is used to represent files or folders, through the file class, you can perform rich operations on files and folders, and can get the file path, size, file name and other information, through the file class Creatnewfile () method to create a file, Delete the file through the Delete () method and rename the file using the Renameto () method.

Import Java.io.file;import Java.io.ioexception;public class Hellofile {public static void main (string[] args) {//TODO Aut o-generated method Stubfile File = new file ("Hello.txt");//default exists relative path, that is, under the project//file file = new file ("Bin/hello.txt");// The file exists in the specified absolute path under//file file = new file (". /hello.txt ");//The file exists at the previous level of the project path//file file = new file (". /.. /hello.txt ");//The file exists at the previous level of the project path above//determine if the file exists if (file.exists ()) {//print" File "Property System.out.println (File.isfile ());//print" Path (folder) "Property System.out.println (File.isdirectory ()),////same directory rename//file nameto = new File (" NewHello.txt ");// File.renameto (Nameto);////cross-Directory rename////Note 1: The folder structure must be in the same partition////NOTE 2: If the file is in a different partition, you need to use a copy of the file instead of renaming//file Nameto = new File ( "Src/newhello.txt");//file.renameto (nameto);////Delete file//file.delete ();//system.out.println ("File Delete succeeded! ");} ELSE{SYSTEM.OUT.PRINTLN ("file does not exist!) "); try {file.createnewfile (); System.out.println ("The file has been created successfully!") ");} catch (IOException e) {System.out.println ("The file cannot be created! ");}}}}



2. Creating, renaming, deleting folders


The main content includes creating folders by using the mkdir () and Mkdirs () methods, deleting folders using the Delete () method, renaming folders using the Renameto () method

Import Java.io.file;public class Hellofolder {public static void main (string[] args) {//Create a single-level folder: Folder.mkdir () File Folder1 = new File ("MyFolder1"),//if (Folder1.mkdir ())//{//system.out.println ("Single-level folder creation complete!") ");//}//else//{//if (Folder1.exists ())//{//system.out.println (" single-level folder already exists, do not create! ") //}//else//{//system.out.println ("Single-level folder creation failed!"); ");//}//}//Create a multilevel folder: Folder.mkdirs () file Folder2 = new File (" Myfolder2/one/two ");//if (Folder2.mkdirs ())//{// System.out.println ("Multilevel folder creation is complete! ");//}//else//{//if (Folder2.exists ())//{//system.out.println (" Multilevel folder already exists, do not create! //}//else//{//system.out.println ("Multilevel folder creation failed!"); ");//}//}////folder rename////Rename the same level folder//file Newfolder1 =new File (" MyFolder3 ");//if (Folder1.renameto (newfolder1))//{// System.out.println ("done!"); /}else{//system.out.println ("fail!"); /}////renaming folders of different levels, a bit similar to moving, but still categorized as renaming////Note://file newfolder2 =new File ("Myfolder2/two") in the same partition;//if (Folder2.renameto (Newfolder2)) {//system.out.println ("done!"); /}else{//system.out.println ("fail!"); /}//Delete Folder if (Folder1.delete ()) {System. out.println ("Delete done! ");} Else{system.out.println ("Delete failed! ");} Note: You can only delete empty folders//folder2.delete ();}}



3, read the file attributes


The main contents include judging whether the file exists, file name, path, file size, whether it is hidden, readable and writable, or not.

Import Java.io.file;public class Readfileproperty {public static void main (string[] args) {File file = new file ("Text.txt" );//Determine if the file exists System.out.println ("file exists" +file.exists ());//Read file name System.out.println ("Read file name" +file.getname ());// Read file path (relative path) System.out.println ("Read file relative path" +file.getpath ());//Read absolute path System.out.println ("Read file absolute path" + File.getabsolutepath ());//Read File Parent path System.out.println ("Read file parent path" +file.getparent ());// Returns the upper-level System.out.println of the relative path ("Read file parent path" + New file (File.getabsolutepath ())). GetParent ());//returns the upper level of the absolute path// Read File size System.out.println ("Read File Size" +file.length () + "byte"); SYSTEM.OUT.PRINTLN ("Read File size" + (float) file.length ()/1000+ "KB");//Determine if the file is hidden System.out.println ("Determine if the file is hidden" + File.ishidden ());//Determine whether the file is readable System.out.println ("Determine if the file is readable" +file.canread ());//Determine if the file is writable System.out.println (" Determine if the file can be written "+file.canwrite ()");//Determine if the file is a folder System.out.println ("Determine if the file is a folder" +file.isdirectory ());}}



4. Settings for file attributes


The main content includes setting up the file as readable, writable, or read-only.

Import Java.io.file;import Java.io.ioexception;public class Setfileproperty {public static void main (string[] args) { File File = new file ("Text.file"); if (File.exists ()) {System.out.println ("files exist, do not create! ");//First confirm the file's attribute System.out.println (" readable? "). "+file.canread ()); System.out.println ("Can write?" "+file.canwrite ()); System.out.println ("Executable?"). +file.canexecute ());//Set the file to writable//file.setwritable (false),//true writable false not writable//set the file as readable//file.setreadable (false); /true read false unreadable//set the file as read-only file.setreadonly ();//confirm the file's attribute System.out.println ("\ n"); System.out.println ("readable?") "+file.canread ()); System.out.println ("Can write?" "+file.canwrite ()); System.out.println ("Executable?"). "+file.canexecute ());} Else{system.out.println ("The file does not exist, please create a new file!") "); try {file.createnewfile ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}



5. Traverse the folder


The main content includes getting all the items in the folder by using the Listfiles () method, and displaying the complete hierarchy recursively.

Package Com.hqu.filetraverse.main;import Java.io.file;public class Traverse {public static void main (string[] args) { Printfiles (New file ("/job/java/workspace/filetraverse"), 1);//Use absolute path//printfiles (". /filetraverse "), 1);//default use relative path}public static void Printfiles (File Dir,int tab) {if (Dir.isdirectory ()) {file next[] = Dir.listfiles ();//The return value is a file and a folder that exists in the array for the (int i=0;i<next.length;i++) {for (int j=0;j<tab;j++) {//Output |-- As the identification level of the tag System.out.print ("|--"),//use print instead of println, you can avoid each time the line break}system.out.println (Next[i].getname ());// Prints the name of the file or folder if (Next[i].isdirectory ()) {printfiles (next[i],tab+1);//recursively calls itself}}}}}



6. Simple reading and writing of files


The main contents include the use of FileInputStream and FileOutputStream, to realize the reading and writing of text files.

Package Com.hqu.rwfile;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.inputstreamreader;import Java.io.outputstreamwriter;import Java.io.unsupportedencodingexception;public class ReadFile {public static void main (string[] args) {File file = new file (" Text.txt "); Create well beforehand and enter the content if (file.exists ()) {//system.out.println ("exit"); System.err.println ("Exit");//System output try {//Prepare three streams for file input FileInputStream fis = new FileInputStream (file);// The input stream of the file belongs to the byte stream inputstreamreader ISR = new InputStreamReader (FIS, "UTF-8"),//inputstreamreader is a character stream, "UTF-8" is encoded for the specified text, Prevents garbled bufferedreader br = new BufferedReader (ISR);//readerstring line;//with buffers for temporary storage of read data while (line = Br.readline ())! = null) {System.out.println (line);} Close input stream br.close (); Isr.close (); Fis.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (Unsupportedencodingexception e) {E.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}} File NewFile = new file ("Newtext.txt");//No need to create, the system automatically creates files when writing try {fileoutputstream fos = new FileOutputStream (newfile); O Utputstreamwriter OSW = new OutputStreamWriter (FOS, "UTF-8"); BufferedWriter bw = new BufferedWriter (OSW), Bw.write ("abcd\n"), Bw.write ("efgh\n"), Bw.write ("ijkl\n"); Bw.write (" Mnop "),//bw.write (" Long Song Line Han Yuefu "),//bw.write (" Green Garden in Kwai, Morning Dew to the day XI. " \ n ");//bw.write (" Yangchun cloth, all things are bright. " \ n ");//bw.write (" Often feared autumn festival to, Kun Huang leaf decline. \ n ");//bw.write (" When the Hundred East Sichuan to the sea, when the return? ") \ n ");//bw.write (" An idle youth, needy age! \ n "); Bw.close (); Osw.close (); Fos.close (); System.out.println ("Write Complete! ");} catch (FileNotFoundException e) {e.printstacktrace ();} catch (Unsupportedencodingexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Learning (eight): Java file programming

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.