[Java Video Note]day20

Source: Internet
Author: User

File class

1. To encapsulate a file or folder as an object

2. Easy to manipulate the property information of files and folders (flow can only manipulate data)

3. The file object can be passed as a parameter to the constructor of the stream

Common methods for file classes:

1. Create

Boolean createnewfile (); Creates a file at the specified location, if the file already exists, is not created, returns false. Unlike the output stream, the output stream object creates a file and the file already exists, then covers it.

Boolean mkdir (): Create Folder

Boolean mkdirs (): Create a multilevel folder

2. Delete

Boolean delete (); Delete Failed returns false

void Deleteonexit ();//delete the specified file when the virtual machine exits

3. Judging

Boolean exists ();//File exists

Isfile ();

Isdirectory ();

Ishidden ();

Isabsolute ()//is an absolute path

4. Access to Information

GetName ();

GetPath ();

GetParent ();

GetAbsolutePath ();

Long LastModified ();//Last Modified time

Long length ();//File size

Import Java.io.*;class day20{public static void Main (string[] args) throws Ioexception{method_5 (); public static void Method_5 () {File F1 = new File ("file.txt"); File F2 = new file ("Haha.txt"); Sop (F1.renameto (F2));} public static void Method_4 () {File F = new file ("file.txt");//file can exist or there can be no sop ("Path:" +f.getpath ());//relative path SOP ("Abspath : "+f.getabsolutepath ());//absolute path SOP (" Parent: "+f.getparent ());//The method returns the absolute path of the file parent directory///If it gets a relative path, returns NULL, Like the file.txt above. If there is a//up-level directory in the relative path, then the directory is the result}public static void Method_3 () throws ioexception{file F = new File ("file.txt"); F.createnewfile ();//Remember that in determining whether a file object is a file or a directory, you must first determine whether the contents of the File/object encapsulation are present and judged by exists. SOP ("dir:" +f.isdirectory ()), SOP ("File:" +f.isfile ()), SOP (F.isabsolute ());//is absolute path}public static void Method_2 () { File F = new file ("File.txt"),//sop ("Execute:" + f.canexecute ()), SOP ("exists:" +f.exists ());} public static void Method_1 () throws ioexception{file F = new File ("file.txt");//f.deleteonexit ();//delete when virtual machine exits, It doesn't matter if there's an exception in the Middle//sop ("Create:" + f.createnewfile ()); SOP ("Delete:" +f. Delete ());//Create folder (directory) file dir = new file ("abc"), Sop ("mkdir:" +dir.mkdir ());//file dirs = new File ("ABC\\D\\KK\\FF\\FDG ");//dirs.mkdirs ();} Create file object public static void Consmethod () {//A.txt encapsulated as a file object, you can encapsulate existing and non-appearing//files or folders into the object file F1 = new file ("C:\\a.txt"); File F2 = new file ("C:\\abc", "b.txt"); File D = new file ("C:\\abc"); File F3 = new file (d, "c.txt"), SOP ("F1:" + F1), SOP ("F2:" + F2), SOP ("F3:" + F3); File F4 = new file ("C:" +file.separator+ "abc" +file.separator+ "T.txt"),//file.separator is delimiter, can cross platform}public static void SOP (Object obj) {System.out.println (obj);}}

Lists all files and directories in the specified directory (without files in subdirectories)

Import java.io.*;class  day20{public static void Main (string[] args) throws ioexception{file dir = new File ("D:\\java_ Day18 ");//directory and file object under current directory (does not contain files in subdirectories) file[] files = dir.listfiles (); for (file f:files) {SOP (F.getname () +":: "+f.length ( ));}} public static void ListDemo2 () {File Dir = new File ("D:\\java_day18"); string[] arr = dir.list (new FilenameFilter ()//file name filter {public boolean accept (file dir, String name) {//sop (dir+ "..." +name) ; return Name.endswith (". txt");//display only. txt file}}); sop (arr.length); for (String Name:arr) {SOP (name);}} public static void Listdemo ()//print the name of the file and folder under the C disk {file F = new file ("c:\\"); string[] names = F.list ();//The file object that calls the list method must be encapsulated in a directory,//The directory must also exist for (String name:names) {SOP (name);}} public static void Listrootsdemo ()//print out all the drive characters  c:\\   d:\{file[] files = file.listroots (); for (File f:files) {SOP (F );}} public static void Sop (Object obj) {System.out.println (obj);}}

Lists the files or folders in the specified directory, including the contents of subdirectories. This is the list of all content in the specified directory.

Because there are directories in the directory, just use the same function that lists the directory functions to complete. You can also call this feature again if the directory appears in the listing process. That is, the function itself calls itself. This form of representation, or programming technique, is called recursion.

Recursion to note:

1. Qualifying Conditions

2. Be aware of the number of recursion and avoid memory overflow.

Import java.io.*;class  day20{public static void Main (string[] args) throws ioexception{file dir = new File ("D:\\java_ Day18 "); Showdir (dir, 0);} public static String Getlevel (Int. level)//simple is to make the display intuitive some {StringBuilder sb = new StringBuilder (); sb.appendfor (int x = 0; x &l T Level X + +) {sb.append ("|--");} return sb.tostring ();} public static void Showdir (File dir, int. level) {SOP (Getlevel (level) +dir);//print under directory level++; file[] files = dir.listfiles (); for (file file:files) {if (File.isdirectory ())) Showdir (file, level); Elsesop (Getlevel ( level) +dir);}} public static void Sop (Object obj) {System.out.println (obj);}}

Output:

D:\java_day18

|--d:\java_day18

|--d:\java_day18

|--d:\java_day18

|--d:\java_day18

|--d:\java_day18

|--d:\java_day18

|--d:\java_day18

|--d:\java_day18\hello

|--|--d:\java_day18\hello

|--d:\java_day18

Deletes a directory with content.

Removal principle:

In Windows, deleting a directory is removed from the inside out.

Since it is removed from the inside, it is necessary to use recursion.

Import java.io.*;class  day20{public static void Main (string[] args) throws ioexception{file dir = new File ("D:\\java_ Day18 "); RemoveDir (dir);} public static void RemoveDir (File dir) {file[] files = Dir.listfiles (), for (int x = 0; x < files.length; x + +) {if (!files[ X].ishidden () && files[x].isdirectory ()) RemoveDir (Files[x]); Elsesop (files[x].tostring () + "..." +files[x].delete ());} SOP (Dir.tostring () + "....>>>" +dir.delete ());} public static void Sop (Object obj) {System.out.println (obj);}}


Exercise: Store the absolute path of a TXT file in a specified directory into a text file. Create a TXT file list file.

Ideas:

1. Recursively for the specified directory.

2. Gets the path of all txt files in the recursive process.

3. Store these paths in the collection.

4. Write the data in the collection to a file.

Import java.io.*;import java.util.*;class day20{public static void Main (string[] args) throws ioexception{file dir = new File ("D:\\java_day18"); list<file> list = new arraylist<file> (); Filetolist (dir, list);//sop (List.size ()); File File = new file (dir, "JavaList.txt"); WriteToFile (list, file.tostring ());} Save the absolute path of all. txt files in the Dir directory to the list collection public static void Filetolist (File dir, list<file> List) {file[] files = Dir.listfiles (); for (file file:files) {if (File.isdirectory ()) filetolist (file, list); Else{if (File.getname (). EndsWith (". txt")) List.add (file);}} Writes the absolute path of the file in the collection of absolute paths to the file to the public static void WriteToFile (List<file> List, String javalistfile) throws Ioexception{bufferedwriter BUFW = NULL;TRY{BUFW = new BufferedWriter (new FileWriter (Javalistfile)); for (File f:list) { String path = F.getabsolutepath (); bufw.write (path); Bufw.newline (); Bufw.flush ();}} catch (IOException e) {throw e;} Finally{try{if (BUFW! = null) Bufw.close ();} catch (IOException e) {throw e;}}} public static void SOP (Object obj) {System.out.println (obj);}} 

Properties is a subclass of Hashtable. This means that it has the characteristics of the map collection, and that the key-value pairs stored in it are strings. is a collection container in combination with IO technology.

The object features: a configuration file that can be used for key-value pairs.

When loading data, you need to have a fixed format for the data: Key = value

Import java.io.*;import java.util.*;class day20{public static void Main (string[] args) throws Ioexception{method_2_ Loaddemo ();} How to store data in a stream in a collection//you want to save the Info.txt key value data in the collection into the//info.txt of the operation in the following://zhangsan=40//lisi=50/*1. Associating a stream with a Info.txt file 2. Reads a row of data, dividing the row data with ' = ' 3. The left side of the equal sign is the key, and the right is the value, which is stored in the Properties collection to */public the static void Method_2_loaddemo () Throws Ioexception{fileinputstream fis = new FileInputStream ("Info.txt"); Properties prop = new properties ();//load the data in the stream into the set prop.load (FIS);//packaged//sop (prop);p rop.list (System.out);// Lists the collection directory Prop.setproperty ("Zhangsan", "100");//modifies the memory, but does not modify the data in the file FileOutputStream fos = new FileOutputStream ("Info.txt") ;p Rop.store (FOS, "midified");p rop.list (System.out);//List Collection directory Fos.close (); Fis.close ();} public static void Method_1 () throws Ioexception{bufferedreader Bufr = new BufferedReader (New FileReader ("Info.txt")); String line =null; Properties prop = new properties (), while (line = Bufr.readline ()) = null) {string[] arr = line.split ("=");p Rop.setpropert Y (Arr[0], arr[1]);} Bufr.close (); SOP (prop);} Set and get element public static void Setandget () {Properties prop = new Properties ();p rop.setproperty ("Zhangsan", "30"); Prop.setproperty ("Lisi", "Max");//sop (prop); String value = Prop.getproperty ("Lisi"), SOP (value),//Output 40//Modify Prop.setproperty ("Lisi", "89");//Get All set<string > names = Prop.stringpropertynames (); for (String s:names) {SOP (s+ ":" +prop.getproperty (s));}} public static void Sop (Object obj) {System.out.println (obj);}}

Used to record the number of application runs. If the number of uses has been reached, then the registration prompt is given.

It is easy to think of: counter. However, the counter is defined in the program and is present in memory as the program runs and is self-incremented. But as the application exits, the counter also disappears in memory. The next time you start the program again, start counting again from 0. It's not what we want. Want is the program even if the end, the value of the counter is also present, the next time the program starts, the value of the counter will be loaded first and then stored again after 1. Therefore, a configuration file is created to record the number of times the software is used.

The configuration file uses the form of a key-value pair. This makes it easy to read data and manipulate the data. The key-value pair data is a map collection, which is stored as a file, using IO technology. So map+io-àproperities. Profiles enable sharing of application data.

Import Java.io.*;import java.util.*;class  day20{public static void Main (string[] args) throws ioexception{ Properties prop = new properties (); The file File = new file ("Count.ini"), or//first encapsulated into a Document object, you can determine the existence of the IF (! File.exists ()))//file does not exist, create a file.createnewfile (); FileInputStream fis = new FileInputStream (file);p rop.load (FIS); int count  = 0; String value = Prop.getproperty ("Time"), if (value = null) {count = Integer.parseint (value), if (Count >= 5) {SOP ("DATE Out "); return;}} Count + +;p Rop.setproperty ("Time", count+ ""); FileOutputStream fos = new FileOutputStream (file);p rop.store (FOS, ""); Fos.close (); Fis.close ();} public static void Sop (Object obj) {System.out.println (obj);}}

Print Flow

This flow provides a way to print all types of data as they are printed.

PrintStream byte Print stream

parameter types that the constructor can accept:

1. File Object File

2. String path

3. Byte output stream OutputStream

PrintWriter character Print stream

1. File Object File

2. String path

3. Byte output stream OutputStream

4. Character output stream Writer

import java.io.*;import java.util.*; class day20{publicstatic void Main (string[] Ar GS) throws IOException {bufferedreaderbufr = new BufferedReader (New InputStreamReader (system.in                   ));                   Printwriterout = new PrintWriter (System.out, true);                   Save to file Printwriterout = new PrintWriter (New FileWriter ("A.txt", true));                  True to automatically refresh Stringline = null for println line break;                                     while (line = Bufr.readline ()) = null) {if (' over '. Equals (line))                            Break                            Out.println (Line.touppercase ());                   Out.flush (); If there is true in front, you do not have to write this sentence} out.close ();         Bufr.close ();         } publicstatic void sop (Object obj) {System.out.println (obj); }}


Sequence Flow

Sequenceinputstream



Multiple streams become a stream

Save the contents of 1.txt 2.txt 3.txt three files to a file in 4.txt

Import Java.io.*;import java.util.*;class  day20{public static void Main (string[] args) throws Ioexception{vector <FileInputStream> v = new vector<fileinputstream> (), V.add (New FileInputStream ("1.txt")); V.add (new FileInputStream ("2.txt")); V.add (New FileInputStream ("3.txt")); Enumeration<fileinputstream> en = v.elements (); Sequenceinputstream sis = new Sequenceinputstream (en);//Multiple Stream object programming one stream FileOutputStream fos = new FileOutputStream ("4.txt") ; byte[] buf = new Byte[1024];int len = 0;while (len = Sis.read (BUF))! =-1) {fos.write (buf, 0, Len);} Fos.close (); Sis.close ();} public static void Sop (Object obj) {System.out.println (obj);}}

Next can be combined to cut

Import java.io.*;import java.util.*;class day20{public static void Main (string[] args) throws Ioexception{merge ();} public static void Splitfile () throws Ioexception{fileinputstream fis = new FileInputStream ("x.jpg"); FileOutputStream fos = null;byte[] buf = new byte[1024 * 1024];//1mint len = 0;int count = 1;while (len = Fis.read (BUF))! =-1)//save one file per 1M {fos = new FileOutputStream ("splitfiles\\" + (count++) + ". Part"), Fos.write (buf, 0, Len); Fos.close ();} Fis.close ();} public static void Merge () throws ioexception//merge cut file {arraylist<fileinputstream> al = new arraylist< Fileinputstream> (); for (int x = 1; x<= 7; x + +) {Al.add (New FileInputStream ("Splitfiles\\" +x+ ". part"));} Final iterator<fileinputstream> it = Al.iterator ();//The following anonymous inner class has access to it, so this is the final decoration enumeration< Fileinputstream> en = new enumeration<fileinputstream> () {public boolean hasmoreelements () {return It.hasnext ( );} Public FileInputStream nextelement () {return It.next ();}}; Sequenceinputstream sis = new SequenceinPutstream (en); FileOutputStream fos = new FileOutputStream ("victory.jpg");//merge into the file byte[] buf = new byte[1024 * 1024];int len = 0;while ((l En = Sis.read ())! =-1) {fos.write (buf, 0, Len);} Fos.close (); Sis.close ();} public static void Sop (Object obj) {System.out.println (obj);}}



[Java Video Note]day20

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.