File class
used to encapsulate a file or folder as an object.
facilitates the operation of File and folder property information.
the file object can be passed as a parameter to the constructor of the stream.
Common methods of the </pre></div><div></div>Get the system root exampleImport java.io.*;p Ublic class FileDemo2 {/** * @param args */public static void main (string[] args) {//TODO auto-generate D Method Stub Listdemo ();} public static void Listdemo () {file F = new File ("d:\\"); String[] names= f.list ();//The object that calls the list method must encapsulate a directory, and the encapsulated file returns null for (String name:names) {System.out.println (name);}} public static void Listrootsdemo () { file[] files=file.listroots (); for (File f:files) { System.out.println (f);}} }
Recursive output file listImport java.io.*;/* lists the files or folders under the specified directory, including the contents of subdirectories. This is the list of all content in the specified directory. Recursive note 1 note to have end 2 to notice the number of recursion to prevent memory overflow */public class FileDemo3 {/** * @param args */public static void main (string[] args) {// TODO auto-generated Method Stub file f= new file ("D:\\u disk Backup"); Showdir (f,0); System.out.println (Getsum (10));} public static String Getlevel (Int. level) {StringBuilder sb= new StringBuilder (); for (int i=0; i<level;i++) {Sb.append (""); } sb.append ("|--"); return sb.tostring (); } public static void Showdir (File dir, int. level) {SYSTEM.OUT.PRINTLN (Getlevel (level) +dir.getname ()); level++; File[] files= dir.listfiles (); for (int i=0;i<files.length;i++) {if (Files[i].isdirectory ()) Showdir (Files[i],level); Else System.out.println (Getlevel (level) +files[i]); }}//Supplement: Recursive method sum public static int getsum (int num) {if (num==1) return 1; else return Num+getsum (- -num); }}
Delete a folder instanceImport java.io.*;/* * Delete the folder you want to delete the file inside. So we're going to use recursion. * Remove files from inside * */public class Fileremovedir {/** * @param args */public static void main (string[] args) {//To Do auto-generated method stub File file= new file ("D:\\abc"); RemoveDir (file);} public static void RemoveDir (File dir) { file[] files =dir.listfiles (); for (int i=0;i<files.length;i++) { if (files[i].isdirectory ()) { removedir (files[i]); } else System.out.println (files[i].tostring () + "file:" +files[i].delete ()); } System.out.println (dir+ "dir:" +dir.delete ());} }
Find folder The specified type is saved in the fileImport Java.io.*;import java.util.*;/* Stores the absolute path of a Java file in a specified directory into a file. Create a list of Java file listings. Idea: 1. Recursively for the specified directory. 2. Gets the path of all Java files for the recursive process. 3. Store these paths in the collection. 4. Write the data in the collection to one. * */public class Javafilelist {/** * @param args * @throws ioexception */public static void Main (string[] args) throws IO Exception {//TODO auto-generated method Stubfile dir = new File ("D:\\u disk Backup"); list<file> list= new arraylist<file> (); filetolist (dir,list); File f =new file ("JavaList.txt"); WriteToFile (list,f);} 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 (". Java")) List.add (file); }}} public static void WriteToFile (List<file> List, File f) throws IOException {BufferedWriter bw= New BufferedWriter (new FileWriter (f)); try{for (File file:list) {String path= file.geTabsolutepath (); Bw.write (path); Bw.newline (); Bw.flush (); }}catch (Exception e) {throw new RuntimeException ("Failed! "); } finally{try{if (bw!=null) bw.close (); }catch (Exception ex) {throw new RuntimeException ("Shutdown failed! "); } } }}Propreties subclasses of the collection class hashtable associated with a stream Import Java.io.*;import java.util.*;p ublic class Propertiesdemo {/** * @param args * @throws ioexception */public static void Main (string[] args) throws IOException {//TODO auto-generated Method Stub//setandget ();//method_ 1 (); Loaddemo ();} The Load method loads a collection of files. public static void Loaddemo () throws Ioexception{fileinputstream fis= new FileInputStream ("Info.txt"); Properties prop= new Properties ();p rop.load (FIS);p rop.list (System.out);p rop.setproperty ("Wangwu", "25"); FileOutputStream fos= New FileOutputStream ("Info.txt");p rop.store (fos, "haha");} The key-value data in the info.txt is stored in the collection for operation. /* Step: 1. Associate with a stream and a info.txt file. 2. Read a row of data and use "=" to cut the data. 3. The left side of the equals sign is built and the right Guardian value. Deposit in the Porperties collection. */public static void Method_1 () throws Ioexception{bufferedreader br= new BufferedReader (New FileReader ("Info.txt")); String Line=null; Properties prop= new Properties (), while ((Line=br.readline ())!=null) {string[] s=line.split ("=");p Rop.setproperty (s[ 0], s[1]);} SYSTEM.OUT.PRINTLN (prop);} Set and get element public static void Setandget () {PrOperties prop = new Properties ();p rop.setproperty ("Zhangsan", "a");p Rop.setproperty ("Lisi", "22"); SYSTEM.OUT.PRINTLN (prop); String value =prop.getproperty ("Zhangsan"); System.out.println (value); set<string> names = Prop.stringpropertynames (); for (String name:names) {System.out.println (Prop.getproperty ( name));}}}
use limit of properties implementation program/* The number of times the application is logged. If the number of uses has been reached, then the registration information is given. Idea: The Properties property file will use the number of times the property exists in this file, each time using the Count property is modified and re-saved to the property file, this operation is to borrow the properties object to operate. Property files are used to store key-value pairs. This makes it easy to manipulate data. A key-value pair is a map collection of data that is stored as a file, using IO data. */import java.io.*;import java.util.*;p ublic class Propertiescount {/** * @param args * @throws ioexception */public Stat IC void Main (string[] args) throws IOException {//TODO auto-generated method stub Properties prop = new Propertie S (); File file= New file ("Count.ini"); if (!file.exists ()) file.createnewfile (); FileInputStream fis = new FileInputStream (file); Prop.load (FIS); int count=0; String value= Prop.getproperty ("Time"); if (value!=null) {count =integer.parseint (value); if (count>=5) {System.out.println ("Hello, the number of use has been paid"); Return }} count++; Prop.setproperty ("Time", count+ ""); FileOutputStream fos = new FileOutputStream (file); Prop.store (FOS, "haha");} }
the use of PrintStream and printwriter print streams/* Print flow for easy printing of various data types. the byte print stream PrintStream can receive a parameter of type 1.file object File 2. String path. String 3. Byte output stream OutputStream PrintWriter can receive parameters of type 1.file object File 2. String path. String 3. Byte output stream outputstream 4. Character output stream Writer */import java.io.*;p ublic class Printstreamdemo {/** * @param args * @throws io Exception */public static void Main (string[] args) throws IOException {//TODO auto-generated method stub Buffere Dreader bufr= New BufferedReader (New InputStreamReader (system.in)); PrintWriter out = new PrintWriter (system.out); String line = null; while ((Line=bufr.readline ())!=null) { out.println (line.touppercase ()); Out.flush (); } Out.close (); Bufr.close (); <pre name= "code" class= "Java" >
}}
DataInputStream and DataOutputStream basic data manipulation flowImport java.io.*;/* DataStream class is primarily used to manipulate the reading and writing of streams of basic data types */public class Datainputstreamdemo {/** * @param args * @throws Except Ion */public static void Main (string[] args) throws Exception {//TODO auto-generated Method Stub//writedata (); /readdata (); Writeutfdemo ();} public static void Writeutfdemo () throws ioexception{DataOutputStream dos = new DataOutputStream (New FileOutputStream (" Data.txt ")); Dos.writeutf ("Hello"); Dos.close ();} public static void ReadData () throws exception{datainputstream dis = new DataInputStream (New FileInputStream ("Data.txt") ); int num =dis.readint (); Boolean b= Dis.readboolean ();d ouble d= dis.readdouble (); SYSTEM.OUT.PRINTLN ("num:" +num); System.out.println ("B:" +b); System.out.println ("D:" +d);} public static void WriteData () throws IOException {DataOutputStream dos = new DataOutputStream (New FileOutputStream ("Data.txt")); Dos.writeint (234); Dos.writeboolean (TRUE); Dos.writedouble (444.456); Dos.close (); }}
ObjectInputStream and ObjectOutputStream object manipulation flows Import java.io.*;p Ublic class Objectstreamdemo {/** * @param args * @throws ioexception */public static void Main (string[ ] args) throws Exception {//TODO auto-generated Method Stub writeobj (); Readobj ();} public static void Readobj () throws IOException, IOException, classnotfoundexception{objectinputstream ois = new Objecti Nputstream (New FileInputStream ("Obj.txt")); Person P = (person) ois.readobject (); SYSTEM.OUT.PRINTLN (P); Ois.close (); }public static void Writeobj () throws IOException, Ioexception{objectoutputstream oos=new ObjectOutputStream (new FileOutputStream ("Obj.txt")), Oos.writeobject (New person ("Lisi", "N", "China"); Oos.close (); } class Person implements Serializable {/** * custom */private static final long serialversionuid = 1l;private S Tring name; The member defined by the transient int age;//keyword Transient also cannot be serialized in heap memory and cannot be serialized in the static String country= "CR";//static member cannot be serialized, no longer heap in memory Pers On (String name, int age,string country) {this.name=name; This.agE=age; This.country=country; } public String toString () {return name+ ":" +age+country; } }
PipedInputStream and PipedOutputStream pipeline operation FlowImport java.io.*;p Ublic class Pipedstreamdemo {/** * @param args * @throws Exception */public static void Main (string[] A RGS) throws Exception {//TODO auto-generated method stub pipedinputstream pis= new PipedInputStream (); PipedOutputStream pos= new PipedOutputStream (); Pis.connect (POS); Pipedread read = new Pipedread (PiS); Pipedwrite write = new Pipedwrite (POS); New Thread (Read). Start (); New Thread (Write). Start (); }}class Pipedread implements runnable{private PipedInputStream in; Pipedread (PipedInputStream i) {this.in=i; } @Overridepublic void Run () {//TODO auto-generated method stubtry{byte[] buf = new Byte[1024];int len=in.read (BUF); string s = new string (Buf,0,len); System.out.println (s); In.close ();} catch (Exception e) {throw new RuntimeException ("read failed");}}} Class Pipedwrite implements runnable{private PipedOutputStream pos; Pipedwrite (PipedOutputStream out) {this.pos= out; } @Overridepublic void Run () {//TODO auto-generated Method stubtry{Thread.Sleep (6000);p os.write ("Ge Men lai Le". GetBytes ());p os.close ();} catch (Exception e) {throw new RuntimeException ("Write stream failed! ");}} }
rondomaccessfile Random file read/write streamImport Java.io.*;/*randomaccessfile The class is not a subclass of the IO system but inherits directly from Object but is a member of the IO package because it has the ability to read and write data. An array is encapsulated internally, and the data elements are manipulated by pointers. You can get the position of the pointer through Getfilepointer. The position of the pointer can also be changed by the Seek method. In fact, the byte input stream and the output stream are encapsulated internally. It can be seen through its own constructor that the class can only manipulate files. And the operation file has a fixed pattern. Read-only R read-write RW if it is read-only mode to operate the file, read the existing file into if the asking price does not exist will be an error. If it is read-write, if no file is created, a file is written. */public class Randomaccessfiledemo {/** * @param args * @throws Exception */public static void Main (string[] args) throw s Exception {//TODO auto-generated Method Stub WriteFile (); ReadFile ();} public static void ReadFile () throws ioexception{randomaccessfile RAF = new Randomaccessfile ("Random.txt", "R");//seek Square The use of the method frequently reads the pointer in the file to adjust the position of the reading data Raf.seek (8*3);//Skips the beginning of the 8 bytes to begin reading the data. byte[] buf = new Byte[4]; Raf.read (BUF); String name = new String (BUF); int age= raf.readint (); System.out.println ("Name:" +name); System.out.println ("Age:" +age); Raf.close (); } public static void WriteFile () throws IOException {Randomaccessfile RAF = new RANDOMACCEssfile ("Random.txt", "RW"); Raf.write ("John Doe". GetBytes ()); Raf.write,//write method is a binary form that writes the lowest eight bits. The Raf.writeint (//writeint) method is to write four bytes without garbled characters. Raf.write ("Harry". GetBytes ()); Raf.writeint (99); Raf.seek (8*3);//Skips a 8-byte write Data raf.write ("Week Seven". GetBytes ()); Raf.writeint (98); Raf.close (); } }
Java File class