The file class and Io stream in Java

Source: Internet
Author: User

Tag: Lis des let obj BBB represents the property parameter ToString

File class
Location in java.io bag
Construction Method:
File (string parent, String child)
New file ("d:\\", "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, "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 folder (directory)
Boolean mkdir () Single layer
Boolean mkdirs () multilayer
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. Judging
Boolean isdirectory () tests whether the file represented by this abstract pathname is a directory.
Boolean isfile () tests whether the file represented by this abstract path name is a standard file.
Boolean Ishidden () tests whether the file specified by this abstract path name is a hidden file.

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. Renaming
Boolean Renameto (File dest)
1) renaming----the same directory
2) different directories-----equivalent to clipping

File f= New file ("F:\\bb6.txt");
File f1= New file ("F:\\123\\bb6.txt");
System.out.println (F.renameto (F1));
5. Other
Static file[] Listroots () lists the available file system roots.
Long Getfreespace () free space
Long Gettotalspace () Total capacity
String[] List () lists the files and directories in the directory (sibling 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 a directory, non-hidden files
File[]listfiles (FileFilter filter)
parameter is a filter class
See the procedure below

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: Filtering a file name
File[]listfiles (FilenameFilter filter)
parameter is a filter class
See the procedure below

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 gets a list of files
1) Lists all files
File File = new file ("F:\\aa");
File [] Filearr = File.listfiles (); The directory (Files and directories) represented by
String [] filearr= file.list (); (Files and directories) in the directory represented by
2) filter
File File = new file ("F:\\aa");
FilenameFilter interface for filtering file names.
String[] filenamearr= file.list (filenamefilter filter)
file[] Filenamearr = File.listfiles ( Filenamefilter filter)

File File = new file ("F:\\aa");
FileFilter interface for filtering files.
file[] Filearr = file.listfiles (filefilter filter)

Recursive: Self (method) call self
Example: Use recursion to show all directories and files in the 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 not directory Strs[i]
if (Strs[i].isdirectory ()) {
Listallfile (Strs[i]);
System.out.println ("directory =" +strs[i].getname ());
} else {
SYSTEM.OUT.PRINTLN ("filename =" +strs[i].getname ());
}
}
}
}

IO stream
IO stream: input (output) stream
Located under the Java.io package
Stream action: Read files with the
Stream classification
1) According to the direction of flow (in memory as a reference):
Input stream output stream
2) According to the content of the stream:
BYTE stream (can read and write all files), character stream (read plain text file)
3) According to the function of:
Node stream processing flow (nested on node stream)
Byte stream, and its subclasses are stream
Character Stream, its subclass is writer Reader
FileWriter
File character output stream
Construction Method:
Note: 1) When the object is created, it is given a path to the file.
2) If the file exists on the overwrite, does not exist then create
3) do not want to overwrite, is to use
FileWriter (String FileName, True)
4) Flush () after you finish writing
5) to close the stream after writing
FileReader
File character input stream
Code:
1)
FileWriter FW = new FileWriter ("D:\\1.txt");//file has overwrite, not created
Fw.write ("abc");
Fw.flush ();
Fw.close (); cannot be written after closing
2)
public static void Main (string[] args) {
try {
FileReader FR = new FileReader ("F:\\1.txt");
int ch=0;
while ((Ch=fr.read ())!=-1) {Read to the last return value of-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, starting from the first position of the char array, reading 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); error messages are 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 is a process flow that is to be wrapped outside the node stream to use
2) Improve the efficiency of writing
3) newline newline ()
To create an 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 is a process flow that is to be wrapped outside the node stream to use
2) Improve the efficiency of reading
3) read a line ReadLine ()
To create an 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 ();
}
Copy of File:
public static void Main (string[] args) {
BufferedReader br = null;
BufferedWriter bw = NULL;
try {
br = new BufferedReader (New FileReader ("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 flush ()
To create an object:
public static void Main (string[] args) {
FileOutputStream Fos=null;
try{
FOS = new FileOutputStream ("D:\\cc\\cc8.txt");
Fos.write ("abc". getBytes ());
GetBytes () method to convert 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 flush ()
To create an object:
public static void Main (string[] args) {
try {
FileInputStream fis = new FileInputStream ("D:\\cc\\cc8.txt");
byte [] b = new byte[2];
int len=0;
while (Len =fis.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 a byte
2) is a processing flow
2) with flush ()

To create an 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{//plus Close () method, refer to (Copy of file)}
}

System.in
Get a stream inputstream from the keyboard input
Using 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 \ n 10
}
} catch (IOException e) {
E.printstacktrace ();
}
}

ObjectInputStream ObjectOutputStream
Object input and output stream
Features: 1) write many data types
2) Writing to custom objects
Serialization: Storing objects in hard disk (value of attribute)
Deserialization: Removing an object from the hard disk (the value of the property)
Note: 1) static modified properties cannot be stored in
2) Transient modified properties cannot be stored in the//transient keyword: The tagged member variable does not participate in the serialization process
3) The class that corresponds to the object must implement an interface (NULL interface) serializable interface
4) do not flush ()
5) methods in a class cannot be serialized, only properties can be serialized
Program Demo:
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 ();
}
}

The file class and Io stream in Java

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.