Java Career - Java Foundation - IO(2) - File Class, Properties Class, Print Stream, Sequence Stream (Merge Stream)

Keywords: Java Attribute Windows less

First, File class

I. overview

File class: abstract representation of file and directory pathnames

2. Characteristics:

1) Used to encapsulate files or folders as objects

2) Easy to manipulate attribute information of files and folders

3) Instances of File classes are immutable; that is, once created, the abstract path names represented by File objects will never change.

4) File objects can be used as constructors of parameters passed to streams

 

II. File Object Creation

Way 1:

             File f =new File("a.txt");

Encapsulate a.txt as a File object. Existing and non-existent files or folders can be encapsulated as objects.

Mode 2:

            File f2=newFile("c:\\abc","b.txt");

Pass in the directory path where the file is located along with the file and specify the file path.

Mode 3:

            File d=new File("c:\\abc");

             File f3=new File(d,"c.txt");

Encapsulate file directory paths as objects. Create the file object again. Reduces the association of files with the parent directory.

Little knowledge:

File.separator represents a directory separator that can be used across platforms. It's equivalent to "\" (parallel slash \\\\\ in windows represents the escaped separator, but not in linux system).

 

3. Common methods of File class

1. Create

        booleancreateNewFile();

Create a file at the specified location, and if the file already exists, do not create it, return false. Unlike the output stream, the output stream object creates a file as soon as it is created. And the file already exists and will be overwritten.

boolean mkdir(); // Create folders, only one folder can be created

Example:

        File dir=new File("abc");

dir.mkdir(); //Create the abc folder

boolean mkdirs(); // Create multilevel folders

2, delete

        boolean delete();

// Delete files or directories. The file exists, returns true; the file does not exist or is being executed, returns false.     

void deleteOnExit(); // Delete the specified file when the program exits

3, judgement

boolean canExecute(); // Is it an executable?

boolean exists(); // Does the file exist?

boolean isFile(); // Is it a file?

Boolean is Directory (); // Is it a folder?

Boolean is Hidden (); // Is it a hidden file?

Boolean is Absolute (); // Is the file an absolute path?

Remember: When deciding whether a file object is a file or a directory, you must determine whether the encapsulated content of the file object exists. Judge by exists.

4. Access to Information

String getName(); // Get the filename

        String getPath();

// Get the relative path of the file (that is, get whatever the parameters of the created object are passed in)

        String getParent();

Get the file parent directory. Returns the parent directory in the absolute path. If the relative path is obtained, return null. If there is an upper directory in the relative path, the directory returns the result.

String getAbsolutePath(); // Absolute path to get files

long lastModified(); // Return the last time the file was modified

long length(); //Return file length

5. Listing Files and File Filtering

static File[] listRoots(); // List the available file system root directoriesThat is, the system disc character

        String[] list();

List all files in the current directory, including hiding. The file object that calls the list method must encapsulate a directory. The directory must also exist.

        String[]list(FilenameFilter filter);

// Returns an array of strings to retrieve files or directories in the directory that satisfy the specified filter.

Filename Filter: File name filter is an interface that contains a method, accept(Filedir,String name), which returns boolean type and filters out unqualified files.

File[] listFiles(); // Returns an abstract path name array to retrieve all files and folders under the current folder

File [] ListFiles (Filename Filter filter); // Returns an array of abstract path names to obtain the files or directories in the directory that satisfy the specified filter.

  1. <span style="font-size:14px;">/* 
  2. Exercise: Use String [] list (Filename Filter filter) method to get all. java files in a directory, other files do not. 
  3. Ideas: 1. FilenameFilter is a filter interface, passing in filter objects with anonymous inner classes 
  4.       2,Override the accept(File file,String name) method of the FilenameFilter interface and determine if name is a java file? 
  5.       3,Traversing String type arrays 
  6. */  
  7.   
  8. import java.io.*;  
  9. class  GetJavaFile  
  10. {  
  11.     public static void main(String[] args)   
  12.     {  
  13.         File file=new File("E:\\Java Study\\Practice\\day07");  
  14.         getJavaFile(file);  
  15.     }  
  16.     //Get all. java file methods in a directory  
  17.     public static void getJavaFile(File dir)  
  18.     {  
  19.         //Pass in the FilenameFilter anonymous inner class subclass object and override the accept method  
  20.         String[] javaFile=dir.list(new FilenameFilter()  
  21.         {  
  22.             public boolean accept(File dir,String name)  
  23.             {  
  24.                 return name.endsWith(".java");//Determine whether the filename ends in. java?  
  25.             }  
  26.         });  
  27.   
  28.         System.out.println("len:"+javaFile.length);  
  29.         //foreach  
  30.         for (String s : javaFile )  
  31.         {  
  32.             System.out.println(s);  
  33.         }  
  34.     }  
  35. }  
  36. </span>  


Four, recursion

1, definition

When each loop in a function can also call this function to achieve, that is, the function itself calls itself. This form of expression, or programming technique, is called recursion.

2. Recursive considerations

(a) Limited conditions. To end the loop call, otherwise it's a dead loop.

b. Pay attention to the number of recursions and try to avoid memory overflow. Because each call itself will first execute the next call to its own method, so it will continue to open up new space in stack memory, too many times, will lead to memory overflow.

Example 1

  1. /* 
  2. Requirements: List files or folders under a specified directory, including subdirectories, that is, list all contents under a specified directory (hierarchical). 
  3.  
  4. Analysis, because there are catalogues in the catalogue, only using the same function to list the catalogues can be completed, in the process of listing or catalogues, you can also call this function again, that is, using the principle of recursion. 
  5.  
  6. */  
  7. import java.io.*;  
  8. class  RecursionDemo  
  9. {  
  10.     public static void main(String[] args)   
  11.     {  
  12.         //Associate specified paths  
  13.         File dir=new File("e:\\Java Study\\Practice");  
  14.           
  15.         //List all. java files in the associated path  
  16.         allFileList(dir,0);  
  17.     }  
  18.   
  19.     //List all the contents in the specified directory  
  20.     public static void allFileList(File dir,int level)  
  21.     {  
  22.         //Hierarchical output  
  23.         System.out.println(getLevel(level)+dir);  
  24.         level++;  
  25.         File[] fileArr=dir.listFiles();//Get the abstract path of all files and directories in this directory  
  26.           
  27.         //ergodic  
  28.         for (File file : fileArr)  
  29.         {  
  30.             if(file.isDirectory())  
  31.             {  
  32.                 //If the directory is still a directory, continue to call this function  
  33.                 allFileList(file,level);  
  34.             }  
  35.             else  
  36.                 System.out.println(getLevel(level)+file);//Display (list) files  
  37.         }     
  38.     }  
  39.   
  40.     //Hierarchical list  
  41.     public static String getLevel(int level)  
  42.     {  
  43.         StringBuilder sb=new StringBuilder();  
  44.         sb.append("|--");  
  45.         //For each level of directory, output more specified characters  
  46.         for (int x=level;x>0 ; x--)  
  47.         {  
  48.             //sb.append("|--");  
  49.             sb.insert(0,"|  ");  
  50.         }  
  51.         return sb.toString();  
  52.     }  
  53. }  

Example two

  1. /* 
  2. Delete a directory with content. 
  3. The deletion principle: 
  4. In windows, delete directories from inside to outside. 
  5. Since it's deleted from inside out. Recursion is needed. 
  6.  
  7. */  
  8. import java.io.*;  
  9. class RemoveDir   
  10. {  
  11.     public static void main(String[] args)   
  12.     {  
  13.         //Specified directory  
  14.         File dir=new File("e:\\1");  
  15.         //Delete directory  
  16.         removeDir(dir);  
  17.   
  18.     }  
  19.   
  20.     //Delete incoming directories  
  21.     public static void removeDir(File dir)  
  22.     {  
  23.         File[] files=dir.listFiles();//List all files and folders in the directory  
  24.         //ergodic  
  25.         for (File file : files )  
  26.         {  
  27.             //If it's still a directory and not hidden  
  28.             if(!file.isHidden()&&file.isDirectory())  
  29.                 removeDir(file);//Continue to delete the contents of the directory  
  30.             else  
  31.                 System.out.println(file.toString()+":-file-:"+file.delete());//Delete files  
  32.         }  
  33.         System.out.println(dir+":::dir:::"+dir.delete());//Delete directory  
  34.     }  
  35. }  

Example three

  1. /* 
  2. Practice: 
  3. Stores the absolute path of a java file in a specified directory into a text file. Create a list of Java files. 
  4. Train of thought: 
  5.      1,Recursion of the specified directory. 
  6.      2,Gets the path of all the java files in the recursive process. 
  7.      3,Store these paths in the collection. 
  8.      4,Write the data in the collection to a file. 
  9. */  
  10. import java.util.*;  
  11. import java.io.*;  
  12.   
  13. class  JavaFileList  
  14. {  
  15.     public static void main(String[] args)   
  16.     {  
  17.         //Specified directory  
  18.         File dir=new File("e:/Java Study/Practice");  
  19.           
  20.         //Define a List collection for File objects that store. java files  
  21.         List<File> list =new ArrayList<File>();  
  22.           
  23.         //Call the access file path method  
  24.         fileToList(dir,list);  
  25.           
  26.         //Specify write file  
  27.         File file=new File(dir,"javafilelist.txt");  
  28.         //Call Write File Method  
  29.         writeToFile(list,file);  
  30.       
  31.     }  
  32.     //Gets the absolute path of all java files in the specified folder and stores them in the collection  
  33.     public static void fileToList(File dir,List<File> list)  
  34.     {  
  35.         File[] files=dir.listFiles();//List all files and directories under the dir path.  
  36.         //ergodic  
  37.         for (File file : files)  
  38.         {  
  39.             //If it is a directory, continue to obtain  
  40.             if(file.isDirectory())  
  41.             {  
  42.                 list.add(file.getAbsoluteFile());//Save the parent directory path as well  
  43.                 fileToList(file,list);  
  44.             }  
  45.             //Will be the absolute path to. java files  
  46.             else if(file.getName().endsWith(".java"))  
  47.                 list.add(file);  
  48.         }  
  49.     }  
  50.   
  51.     //Write elements in a collection into a text file  
  52.     public static void writeToFile(List<File> list,File file)  
  53.     {  
  54.           
  55.         BufferedWriter bw=null;  
  56.               
  57.         try  
  58.         {   //Associating Written Files with Character Stream Buffer Objects  
  59.             bw=new BufferedWriter(new FileWriter(file));  
  60.             for (File file0 : list )  
  61.             {  
  62.                 bw.write(file0.getAbsolutePath());//Write in  
  63.                 bw.newLine();//Line feed  
  64.                 bw.flush();//Refresh  
  65.             }  
  66.         }  
  67.         catch (IOException e)  
  68.         {  
  69.             throw new RuntimeException("fail to write to file");  
  70.         }  
  71.         finally  
  72.         {  
  73.             try  
  74.             {  
  75.                 if(bw!=null)  
  76.                     bw.close();//Shut off flow  
  77.             }  
  78.             catch (IOException e)  
  79.             {  
  80.                 throw new RuntimeException("Flow resource shutdown failed");  
  81.             }  
  82.         }  
  83.     }  
  84. }  

 

Lecture 2: Properties class

I. overview

1. Properties is a subclass of Hashtable, which has the characteristics of Map set. It also has stored key-value pairs, which are strings without generic definitions. It is the collection container that the collection neutralization and IO technology want to combine.

2. Characteristics:

Configuration files that can be used in the form of key-value pairs

2) When loading, data needs to be in a fixed format, commonly used as key = value

 

2. Special methods

1, setting up

        Object setProperty(String key,String value);

// Set keys and values, call the Hashtable method put

2. Get

        String getProperty(String key);

//Specify key search value

        Set<String> stringPropertyName();

// Returns the key set of the list of attributes and stores it in the Set set

3. Loading flow and storage inflow

        void load(InputStream ism);

Read the list of attributes (key and element pairs) from the input byte stream. It is also called loading data from streams into collections.

        void load(Readerreader);

Read the list of attributes (key and element pairs) from the input character stream. It is also called loading data from streams into collections.

voidlist(PrintStream out); // Output the list of attributes to the specified output stream

        void store(OutputStreamout,String comments);

The // corresponding load(InputStream) writes the list of attributes (key-value pairs) to the output stream. Description of the comments attribute list.

        void store(Writerwriter, String comments);

The // corresponding load(Reader) writes the list of attributes (key-value pairs) to the output stream. Description of the comments attribute list.

Example

  1. //Demonstrates how to store data in a stream into a collection.  
  2.     //You want to store the key data in info.txt into a collection for operation.  
  3.     /* 
  4.         1,Associate with a stream and info.txt file. 
  5.         2,Read a row of data and cut it with "=". 
  6.         3,The left side of the equal sign acts as the key and the right side acts as the value. Store it in the Properties collection. 
  7.  
  8.     */  
  9.         //Method of Storing File Data into Properties Collection  
  10.     public static void method()throws IOException  
  11.     {  
  12.         //Using Characters to Read Buffer Stream Associated Files  
  13.         BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));  
  14.   
  15.         String line = null;  
  16.         //Define Properties Collection  
  17.         Properties prop = new Properties();  
  18.   
  19.             while((line=bufr.readLine())!=null)  
  20.         {  
  21.             String[] arr = line.split("=");//Segmentation of a row of data by "="  
  22.             //Save = left as key and = right as value  
  23.             prop.setProperty(arr[0],arr[1]);  
  24.         }  
  25.   
  26.         bufr.close();//Shut off flow  
  27.   
  28.         System.out.println(prop);  
  29.     }  

Practice:

  1. /* 
  2. Exercise: Used to record the number of times an application runs. If the number of use has arrived, then give a registration prompt. 
  3.      
  4. Analysis: 
  5. It's easy to think of a counter. However, the counter is defined in the program and disappears in memory as the application exits. 
  6. So we need to create a configuration file to record the number of times the software is used. The configuration file is in the form of key-value pairs. The key-value pair data is a map set. Data is stored in file form. Use io technology. Then map+io - > Properties. 
  7.  
  8. Ideas: 1. Connect text information files with read streams. Read if it exists and create if it does not. 
  9.       2,Every time it runs, it stores the file data into the collection, reads the value and judges the number of times. If it is less than or equal to five times, the number of times will be increased by one time, and if it is larger, the prompt information will be output. 
  10.       3,Store information data with a value less than or equal to five times in a file 
  11. */  
  12. import java.util.*;  
  13. import java.io.*;  
  14.   
  15. class  RunCount  
  16. {  
  17.     public static void main(String[] args)throws IOException   
  18.     {  
  19.         int count=runCount();  
  20.         if(count>5)//If the program has been used more than five times, it will be terminated and prompted  
  21.         {  
  22.             System.out.println("The number of times, pay!!!!!");  
  23.             return ;  
  24.         }  
  25.         else  
  26.             System.out.println("Procedure No."+count+"second Run!");  
  27.     }  
  28.     //Get the number of times the program runs  
  29.     public static int runCount()throws IOException  
  30.     {  
  31.         Properties ps=new Properties();//Creating Collection Objects  
  32.   
  33.         File file=new File("info.ini");//Encapsulation of files  
  34.         if(!file.exists())//Judging whether it exists  
  35.             file.createNewFile();  
  36.         FileReader fr=new FileReader(file);//Associate files with read streams  
  37.           
  38.         ps.load(fr);//Loading file data from the stream into the collection  
  39.   
  40.         int count=0;//Define counters  
  41.         String value=ps.getProperty("time");//Get Number Value  
  42.           
  43.         if(value!=null)//If the overvalue is not equal to null, it is assigned to count.  
  44.         {  
  45.             count=Integer.parseInt(value);  
  46.         }  
  47.         count++;//Self-increment per start  
  48.         ps.setProperty("time",count+"");//Record the number of times in the collection  
  49.   
  50.         FileWriter fw=new FileWriter(file);  
  51.         ps.store(fw,"");//Store data in a collection in a hard disk file  
  52.           
  53.         fr.close();//Shut off flow  
  54.         fw.close();  
  55.   
  56.         return count;//Returns the number of times the program was started  
  57.     }  
  58. }  

 

Lecture 3 Print Stream

I. overview

Print Stream and Print Writer

2. The stream provides a printing method that prints all types of data as they are.

 

2. Byte Print Stream

The type of parameter that can be received in the construction method:

File objects. File

String Path: String

3. Character Output Stream

 

3. String Print Stream: PrintWriter

Acceptable parameter types in construction methods

File object: File

String Path: String

3. Byte Output Stream

4. Character Output Stream: Writer

Example

  1. import java.io.*;  
  2.   
  3. class  PrintStreamDemo  
  4. {  
  5.     public static void main(String[] args) throws IOException  
  6.     {  
  7.         //Keyboard Entry  
  8.         BufferedReader bufr =   
  9.             new BufferedReader(new InputStreamReader(System.in));  
  10.   
  11.         //Print stream associated files, automatically refresh  
  12.         PrintWriter out = new PrintWriter(new FileWriter("a.txt"),true);  
  13.   
  14.         String line = null;  
  15.   
  16.         while((line=bufr.readLine())!=null)  
  17.         {  
  18.             if("over".equals(line))//End character  
  19.                 break;  
  20.             out.println(line.toUpperCase());  
  21.             //out.flush();  
  22.         }  
  23.           
  24.         //Shut off flow  
  25.         out.close();  
  26.         bufr.close();  
  27.   
  28.     }     
  29. }  

 

Sequence Flow

I. overview

1. SequenceInputStream merges multiple streams. Also known as merge flow.

2. Common constructors

        SequenceInputStream(Enumeration<?extends FileInputStream> e)

 

2. Common steps for merging multiple stream files

Create collections and add stream objects to collections

2. Create Enumeration objects and add collection elements.

3. Create SequenceInputStream objects and merge stream objects

4. Create Write Stream Objects and FileOutputStream Associates Write Files

5. Read and write data repeatedly using SequenceInputStream object and FileOutputStream object.

Example:

  1. /* 
  2. SequenceInputStream 
  3. Merging flow 
  4. Requirement: Merge data from three text files into one text file 
  5. Ideas: 1. Create a Vector collection and add three text file byte streams to the collection 
  6.       2,Create an Enumeration object, and create a SequnceInputStream object to associate Enumeration 
  7.       3,Output stream associates new text files 
  8.       4,Repeated reading and writing operations 
  9. */  
  10. import java.util.*;  
  11. import java.io.*;  
  12.   
  13. class  SequenceInputStreamDemo  
  14. {  
  15.     public static void main(String[] args)throws IOException  
  16.     {  
  17.         Vector<InputStream> ve=new Vector<InputStream>();//Create vector s collection and add related stream objects  
  18.         ve.add(new FileInputStream("1.txt"));  
  19.         ve.add(new FileInputStream("2.txt"));  
  20.         ve.add(new FileInputStream("3.txt"));  
  21.   
  22.         Enumeration<InputStream> en=ve.elements();//Create enumeration objects  
  23.         SequenceInputStream sis=new SequenceInputStream(en);//Merging flow  
  24.   
  25.         FileOutputStream fos=new FileOutputStream("4.txt");//Associated Write File  
  26.           
  27.         //Repeated reading and writing operations  
  28.         byte[] buf=new byte[1024];  
  29.         int len=0;  
  30.         while((len=sis.read(buf))!=-1)  
  31.         {  
  32.             fos.write(buf,0,len);  
  33.         }  
  34.           
  35.         //Shut off flow  
  36.         fos.close();  
  37.         sis.close();  
  38.     }  
  39. }  

Practice:

  1. /* 
  2. Cut file 
  3. Requirement: Cut an mp3 file into several parts in 1M size 
  4. Ideas: 1. Use file byte stream to associate mp3 files 
  5.       2,Define a container to store 1M-sized data and write to a new file when the storage is full 
  6.  
  7. */  
  8. import java.util.*;  
  9. import java.io.*;  
  10.   
  11. class  SplitFile  
  12. {  
  13.     public static void main(String[] args) throws IOException  
  14.     {  
  15.         //Specify the file to be cut  
  16.         File file=new File("C:\\Users\\asus\\Desktop\\Suri - The same moonlight.mp3");  
  17.         //Cut the specified file  
  18.         splitFile(file);  
  19.   
  20.         //Specify the files to be merged into  
  21.         File file1=new File("E:\\Java Study\\Practice\\day20\\splitFile\\The same moonlight.mp3");  
  22.         //Merge some files into specified files  
  23.         merge(file1);  
  24.   
  25.     }  
  26.     //Receive a file and cut it in 1M size  
  27.     public static void splitFile(File file)throws IOException  
  28.     {  
  29.         //Associate files to be cut  
  30.         BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));  
  31.           
  32.         BufferedOutputStream bos=null;  
  33.   
  34.         //Define 1M size storage container  
  35.         byte[] buf=new byte[1024*1024];  
  36.         int len=0,x=0;  
  37.         while ((len=bis.read(buf))!=-1)  
  38.         {  
  39.             //Write to a new file every 1M  
  40.             bos=new BufferedOutputStream(new FileOutputStream("E:\\Java Study\\Practice\\day20\\splitFile\\"+(++x)+".part"));  
  41.             bos.write(buf,0,len);  
  42.             bos.close();//Remember to turn off a file before you finish it  
  43.         }  
  44.         //Shut off flow  
  45.         bis.close();  
  46.     }  
  47.   
  48.     //Merge some files into an executable file  
  49.     public static void merge(File file)throws IOException  
  50.     {  
  51.         //Define a collection to store these parts of file association path data  
  52.         ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();  
  53.   
  54.         for (int x=1;x<=6 ; x++)  
  55.         {  
  56.             al.add(new FileInputStream("E:\\Java Study\\Practice\\day20\\splitFile\\"+x+".part"));  
  57.         }  
  58.           
  59.         //Because Enumeration is a Vector-specific iteration method, an anonymous inner class of Enumeration type is created here.  
  60.         final  ListIterator<FileInputStream> it=al.listIterator();  
  61.         Enumeration<FileInputStream> en=new Enumeration<FileInputStream>()  
  62.         {  
  63.             public boolean hasMoreElements()  
  64.             {  
  65.                 return it.hasNext();  
  66.             }  
  67.   
  68.             public FileInputStream nextElement()  
  69.             {  
  70.                 return it.next();  
  71.             }  
  72.         };  
  73.   
  74.         //Associated Enumeration Objects  
  75.         SequenceInputStream sis=new SequenceInputStream(en);  
  76.   
  77.         //Write the merged file data to the specified file  
  78.         FileOutputStream fos=new FileOutputStream(file);  
  79.           
  80.         //Define an array of temporary stored data  
  81.         byte[] buf=new byte[1024];  
  82.         int len=0;  
  83.         while((len=sis.read(buf))!=-1)  
  84.         {  
  85.             fos.write(buf,0,len);//Writing data  
  86.         }  
  87.   
  88.         //Shut off flow  
  89.         fos.close();  
  90.         sis.close();  
  91.   
  92.     }  
  93.   
  94. }

Posted by cryp7 on Fri, 04 Jan 2019 13:36:11 -0800