Let's talk about the file class and IO stream in JAVA and the javafileio in detail.

Source: Internet
Author: User

Let's talk about the file class and IO stream in JAVA and the javafileio in detail.

File class
Location: java. io package
Constructor:
File (String parent, String child)
New file ("d :\\}, example a.txt ")

File (String pathname)
New file ("d: \ a.txt ")

File (File parent, String child)
File f = new File ("d :\\");
File f1 = new file(f,20.a.txt ")

Common Methods:
1. Get
1) file name
String getName ()
2) file path
String getAbsolutePath ()
3) Size
Long length ()
3) last modification time
Long lastModified ()

File file = new File ("d: \ aa.txt ");
System. out. println (file. getName ());
System. out. println (file. getAbsolutePath ());
System. out. println (file. lastModified ());
Long l = file. lastModified ();
Date date = new Date (l );
System. out. println (date. toString ());
System. out. println (file. length ());
2. Create and delete
1) create a file
Boolean createNewFile ()
2) create a folder (directory)
Boolean mkdir () Single Layer
Boolean mkdirs () Multi-Layer
3) delete files and directories
Boolean delete ()

File f = new File ("d: \ B .txt ");
Boolean B = f. createNewFile ();
System. out. println (B );
F. delete ();

File f1 = new File ("d: \ ch1027 ");
F1.mkdir ();
File f2 = new File ("d: \ ch1028 \ ch1029 \ ch1030 ");
F2.mkdirs ();

File f2 = new File ("d: \ ch1028 \ ch1029 \ ch1030 ");
System. out. println (f2.delete ());
3. Judgment
Boolean isDirectory () tests whether the file represented by this abstract path name is a directory.
Boolean isFile () tests whether the file represented by this abstract path name is a standard file.
Boolean isHidden () tests whether the object specified by this abstract path name is a hidden object.

File f1 = new File ("d: \ ch1027 ");
System. out. println (f1.isDirectory ());
System. out. println (f1.isFile ());

File f = new File ("d: \ bb.txt ");
Boolean B = f. createNewFile ();
System. out. println (f. isHidden ());
4. Rename
Boolean renameTo (File dest)
1) same Directory ---- rename
2) Different directories-equivalent to cutting

File f = new File ("f: \ bb6.txt ");
File f1 = new File ("f :\\ 123 \ bb6.txt ");
System. out. println (f. renameTo (f1 ));
5. Others
Static File [] listRoots () lists available File system root.
Long getFreeSpace () available space
Long getTotalSpace () total capacity
String [] list () lists the files and directories in the directory (peer directory)
File [] files = File. listRoots ();
For (int I = 0; I <files. length; I ++ ){
System. out. println (files [I]);
}

File f = new File ("f :\\");
System. out. println (f. getFreeSpace ());
System. out. println (f. getTotalSpace ());

File f = new File ("f :\\ 123 ");
String [] strs = f. list ();
For (int I = 0; I <strs. length; I ++ ){
System. out. println (strs [I]);
}
FileFilter Interface
File Filter
Example: show non-hidden files in a directory
File [] listFiles (FileFilter filter)
The parameter is a filter class.
For more information, see the following procedure.

Public class FilteHidden implements FileFilter {
Public boolean accept (File file ){
Return! File. isHidden ();
}
}
Public class Filess {
Public static void main (String [] args ){
File file = new File ("f :\\ 123 ");
File [] s = file. listFiles (new FilteHidden ());
For (int I = 0; I <s. length; I ++ ){
System. out. println (s [I]. getName ());
}
}
}

FilenameFilter Interface
File Name Filter
Example: filter file names
File [] listFiles (FilenameFilter filter)
The parameter is a filter class.
For more information, see the following procedure.

Public class Filename implements FilenameFilter {
Private String endstr;
Public boolean accept (File dir, String name ){
Return name. endsWith (endstr );
}
Filename (String str ){
Endstr = str;
}
}
Public class FilenameDemo {
Public static void main (String [] args ){
File file = new File ("f :\\ 123 ");
File [] files = file. listFiles (new Filename (". txt "));
For (int I = 0; I <files. length; I ++ ){
System. out. println (files [I]. getName ());
}
}
}

File class to get the File list
1) list all objects
File file = new File ("f: \ aa ");
File [] filearr = file. listFiles (); indicates the directory (File and directory)
String [] filearr = file. list (); indicates the directory (file and directory)
2) Filter
File file = new File ("f: \ aa ");
FilenameFilter interface, used to filter file names.
String [] filenamearr = file. list (FilenameFilter filter)
File [] filenamearr = file. listFiles (FilenameFilter filter)

File file = new File ("f: \ aa ");
FileFilter interface, used to filter files.
File [] filearr = file. listFiles (FileFilter filter)

Recursion: Self (method) calls self
Example: recursively display all directories and files in a directory
Public class B {
Public static void main (String [] args ){
File file = new File ("f :\\ 123 ");
ListAllFile (file );
}
Public static void listAllFile (File file ){
File [] strs = file. listFiles ();
For (int I = 0; I <strs. length; I ++ ){
// Is the directory strs [I]?
If (strs [I]. isDirectory ()){
ListAllFile (strs [I]);
System. out. println ("directory =" + strs [I]. getName ());
} Else {
System. out. println ("file name =" + strs [I]. getName ());
}
}
}
}

IO stream
IO stream: Input (Input) Output stream
Under the java. io package
Stream Function: used to read files
Stream classification
1) by flow (with memory as a reference ):
Input stream output stream
2) stream-based content score:
Byte streams (read and write all files) and bytes streams (read plain text files)
3) by function:
Node stream processing stream (set on the node stream)
Byte Stream. Its subclass is Stream.
Producer stream, which is a subclass of Writer Reader.
FileWriter
File character output stream
Constructor:
Note: 1) when an object is created, the file path must be provided.
2) If the file exists, it will be overwritten. If the file does not exist, it will be created.
3) I don't want to overwrite it.
FileWriter (String fileName, true)
4) flush ()
5) Close the stream after writing.
FileReader
File character input stream
Code:
1)
FileWriter fw = new FileWriter ("d: \ 1.txt"); // overwrite the file. If no, create
Fw. write ("abc ");
Fw. flush ();
Fw. close (); cannot be written after being closed
2)
Public static void main (String [] args ){
Try {
FileReader fr = new FileReader ("f: \ 1.txt ");
Int ch = 0;
While (ch = fr. read ())! =-1) {read the final return value as-1
System. out. println (char) ch );
}
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
3)
Public static void main (String [] args ){
Try {
FileReader fr = new FileReader ("f: \ 1.txt ");
Char [] buf = new char [3];
Int I = fr. read (buf );
System. out. println (new String (buf, 0, I ));
// New String (buf, 0, I) char [] buf, read from the nth position of the char array, read several
Int i1 = fr. read (buf );
System. out. println (new String (buf, 0, i1 ));
} Catch (Exception e ){
E. printStackTrace ();
}
}
4)
Public class FileWriterDemo {
Public static void main (String [] args ){
FileWriter fw = null;
Try {
Fw = new FileWriter ("d: \ 1.txt ");
Fw. write ("fff ");
Fw. write ("ggggg ");
Fw. flush ();
Int I = 10/0;
} Catch (Exception e ){
String str = e. getMessage ();
FileWriterDemo d = new FileWriterDemo ();
D. xie (str); the error message is written to another file.
E. printStackTrace ();
} Finally {
Try {
Fw. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
Public void xie (String str ){
FileWriter fw = null;
Try {
Fw = new FileWriter ("d: \ 2.txt", true );
Fw. write (str );
Fw. flush ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
Try {
Fw. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
BufferedWriter file character output stream with buffer
Features: 1) It processes the stream and needs to be used outside the node stream.
2) Improve write Efficiency
3) newLine ()
Creation object:
1) FileWriter fw = new FileWriter ("d: \ cc \ cc.txt ");
BufferedWriter bw = new BufferedWriter (fw );
2) When no exception is caught
BufferedWriter bw1 = new BufferedWriter (new FileWriter ("d: \ cc \ cc3.txt "));
Bw1.write ("abcbbbb ");
Bw1.newLine ();
Bw1.write ("sssss ");
Bw1.newLine ();
Bw1.write ("defxxx ");
Bw1.flush ();
Bw1.close ();
BufferedReader file character input stream with buffer
Features: 1) It processes the stream and needs to be used outside the node stream.
2) Improve reading efficiency
3) read a row of readLine ()
Creation object:
Try {
BufferedReader br = new BufferedReader (new FileReader ("d: \ cc \ cc.txt "));
String str = null;
While (str = br. readLine ())! = Null ){
System. out. println (str );
}
} Catch (Exception e ){
E. printStackTrace ();
}
File Replication:
Public static void main (String [] args ){
BufferedReader br = null;
BufferedWriter bw = null;
Try {
Br = new BufferedReader (new FileReader (new File ("d: \ cc \ cc.txt ")));
Bw = new BufferedWriter (new FileWriter ("d: \ cc \ cc5.txt "));
String str = null;
While (str = br. readLine ())! = Null ){
Bw. write (str );
Bw. newLine ();
Bw. flush ();
}

} Catch (Exception e ){
E. printStackTrace ();
} Finally {
If (br! = Null ){
Try {
Br. close ();
} Catch (IOException e ){
E. printStackTrace ();
}

}
If (bw! = Null ){
Try {
Bw. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}

FileOutputStream file byte output stream
Features: 1) the output is byte.
2) do not use flush ()
Creation object:
Public static void main (String [] args ){
FileOutputStream fos = null;
Try {
Fos = new FileOutputStream ("d: \ cc \ cc8.txt ");
Fos. write ("abc". getBytes ());
// GetBytes () converts a string into a byte array byte []
Fos. write (97 );
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
If (fos! = Null ){
Try {
Fos. close ();
} Catch (IOException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}
}


FileInputStream file byte input stream
Features: 1) the input is byte
2) do not use flush ()
Creation object:
Public static void main (String [] args ){
Try {
FileInputStream FCM = new FileInputStream ("d: \ cc \ cc8.txt ");
Byte [] B = new byte [2];
Int len = 0;
While (len = FS. read (B ))! =-1 ){
System. out. println (new String (B, 0, len ));
}
} Catch (Exception e ){
E. printStackTrace ();
}
}

BufferedOutputStream BufferedInputStream
Byte output (input) stream with buffer
Features: 1) the output (in) is byte.
2) It is a processing stream.
2) use flush ()

Creation object:
Public static void main (String [] args ){
Try {
BufferedInputStream bis = new BufferedInputStream (new FileInputStream ("d: \ cc \ cc8.txt "));
BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream ("d: \ cc \ cc9.txt "));
Int len = 0;
Byte [] B = new byte [1024];
While (len = bis. read (B ))! =-1 ){
Bos. write (B );
}
Bos. flush ();
} Catch (Exception e ){
E. printStackTrace ();
} Finally {// Add the close () method. For details, refer to (file copy )}
}

System. in
Input a stream from the keyboard.
Use the method in InputStream
Public static void main (String [] args ){
InputStream is = System. in;
Int ch = 0;
Try {
While (ch = is. read ())! =-1 ){
System. out. println (char) ch); // \ r 13 \ n 10
}
} Catch (IOException e ){
E. printStackTrace ();
}
}

ObjectInputStream ObjectOutputStream
Input/output stream of an object
Features: 1) write many data types
2) write custom objects
Serialization: stores objects in the hard disk (attribute value)
Deserialization: Get the object from the hard disk (attribute value)
Note: 1) static modified attributes cannot be saved
2) The properties modified by Transient cannot be stored in the // transient keyword. The Marked member variables do not participate in the serialization process.
3) the class corresponding to the object must implement an interface (empty Interface) Serializable Interface
4) do not use flush ()
5) methods in the class cannot be serialized, and only attributes can be serialized.
Program Demonstration:
Public static void main (String [] args ){
Try {
ObjectOutputStream ous = new ObjectOutputStream (new FileOutputStream (new File ("d: \ cc \ Animal. obj ")));
Animal a1 = new Animal ("aa", 1 );
Ous. writeObject (a1); // serialization
Ous. close ();
ObjectInputStream ois = new ObjectInputStream (new FileInputStream (new File ("d: \ cc \ Animal. obj ")));
Animal an = (Animal) ois. readObject (); // deserialization
System. out. println (an. getAge () + "," + an. getName ());
Ois. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}

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.