Java Learning Notes (15)

Source: Internet
Author: User

1. java.io.File Basic API

File (String)

Long Length ()

Long LastModified ()

String GetName ()

String GetPath ()

Boolean exists ()

Boolean dir.isfile ()

Boolean dir.isdirectory ()

Boolean mkdir ()//Create a directory

Boolean mkdirs ()//create many non-existent directories on the path

Boolean Delete ()

Boolean Creatnewfile () throws IOException

File[] ListFile ()

2. Callback Mode FileFilter

File[] ListFile (filefilter)

Example:

public static void Main (string[] args) {file Dir=new file ("."); /file[] List=dir.listfiles (New Myfilter ()); File[] List=dir.listfiles (<span style= "color: #ff0000;" >new FileFilter () {///anonymous inner class implements public Boolean accept (File pathname) {System.out.println (Pathname.getname ()); return Pathname.getname (). StartsWith (".");}); System.out.println (arrays.tostring (list));} /*static class Myfilter implements filefilter{//static inner class implements public Boolean accept (File pathname) {System.out.println ( Pathname.getname ());//Tracking code return Pathname.getname (). StartsWith (".");}} */

3. Java.io.RandomAccessFile can access (read/write) byte information at any location in a file

Randomaccessfile (file,string) throws FileNotFoundException

ARG0 represents the file to be accessed

Arg1 represents the mode of access

Randomaccessfile maintains a pointer to the location to read and write, and the pointer automatically moves back

int read ()//each time a data is read, the pointer moves backwards

Seek ()//can be used to move the position of the pointer

void write (int)//write Data

Long Getfilepointer ()//Get pointer position

Example:

public static void Main (string[] args) throws Ioexception,filenotfoundexception{file file=new File ("Demo.txt");//file file= New File ("Src/demo.txt"); Randomaccessfile raf=new randomaccessfile (file, "RW"); <span style= "White-space:pre" ></span>// Open file System.out.println in read/write mode (Raf.getfilepointer ()); <span style= "White-space:pre" ></span>// Prints the position of the current pointer int b=raf.read (); <span style= "White-space:pre" ></span>//reads the current pointer to the location of the content System.out.println ( Integer.tohexstring (b)); Raf.close (); <span style= "White-space:pre" ></span>//close file string mail= "1,11"; System.out.println (Readmail ("123.txt", Mail)) <span style= "White-space:pre" ></span>//call Readmail () function Lowcase ("Demo.txt"), <span style= "White-space:pre" ></span>//all the uppercase letters in the file into lowercase} 
<span style= "White-space:pre" ></span>//reads the contents of the corresponding location according to code public static string Readmail (string filename, String code) throws Ioexception{file file=new File (filename); Randomaccessfile raf=new randomaccessfile (file, "R"); <span style= "White-space:pre" ></span>// Open the file in read mode string[] Idx=code.split (","); <span style= "White-space:pre" ></span>//Code segmentation StringBuilder Buf=new StringBuilder (); for (int i=0;i<idx.length;i++) {String S=idx[i];raf.seek (Integer.parseint (s)); <span Style= "White-space:pre" ></span>//move pointer int b=raf.read (); <span style= "White-space:pre" ></span> Read Content char c= (char) b;buf.append (c);} Raf.close (); return buf.tostring ();} Use 123.txt. To encrypt a piece of text, return a code sequence public static void Lowcase (String filename) throws Ioexception{file file=new File (filename); Randomaccessfile raf=new randomaccessfile (file, "RW"); <span style= "White-space:pre" ></span>// Open file in read-write mode long pos=0;<span style= "white-space:pre" ></span>//file pointer position while (Pos<file.lenGth ()) {<span style= "White-space:pre" ></span>//determines whether to reach end of file int b=raf.read (); if (b>= ' A ' &&b< = ' Z ') {<span style= "White-space:pre" ></span>//b is capital letter b=b-' a ' + ' a '; <span style= "White-space:pre" > </span>//uppercase to lowercase raf.seek (raf.getfilepointer ()-1) <span style= "White-space:pre" ></span>// Pointer fallback raf.write (b); <span style= "White-space:pre" ></span>//performs a write operation, the pointer moves down one position, so there is no need to apply seek to adjust the point < Span style= "White-space:pre" ></span>//pin position}pos++;<span style= "White-space:pre" ></span>// }raf.close () for the processed length once per processing, <span style= "White-space:pre" ></span>//close File}
<span style= "White-space:pre" ></span>public static void Main (string[] args) throws Ioexception{file file= New File ("Demo.txt"); Randomaccessfile raf=new randomaccessfile (file, "RW"); <span style= "White-space:pre" ></span>// Open file in read-write mode byte[] buf=new byte[5];<span style= "White-space:pre" ></span>//set BUF size, that is, the size of a read// Reads the data in the file into a byte buffer, returns the read quantity int count=raf.read (BUF), <span style= "White-space:pre" ></span>//calls the Read method with parameters, Read BUF size data into System.out.print (count+ ",") at a time, <span style= "White-space:pre" ></span>// Count indicates the size of the data read System.out.println (arrays.tostring (BUF)); Raf.seek (Raf.length ()); <span style= "White-space:pre" ></span>//moves to the end of the file Raf.write (buf,1,3); <span style= "White-space:pre" ></span>//starts from the first position, Write the BUF successive 3 English characters into file raf.close (); <span style= "White-space:pre" ></span>//close file}/* Reads a small file into a byte array of memory */public static byte[] Read (String filename) throws Ioexception{file file=new File (filename); Randomaccessfile raf=new RandomAccessfile (file, "R"), <span style= "White-space:pre" ></span>//open file int length= (int) raf.length () in read mode; <span style= "White-space:pre" ></span>//get file length byte[] buf=new byte[length];<span style= "White-space: Pre "></span>//declares a bufraf.read (BUF) of the same size as the file, <span style=" White-space:pre "></span>//a batch of reads, Once read raf.close (); <span style= "White-space:pre" ></span>//close file return buf;}

4.java.io.inputstream input stream read to end of file return-1

Java.io.OutputStream output stream

Example:

Input Stream instance:

public static void Main (string[] args) throws Ioexception{readdemo (); Readbybufferdemo (); private static void Readbybufferdemo () throws Ioexception{inputstream in=new FileInputStream ("Demo2.txt"); <span Style= "White-space:pre" ></span>//input stream Open file byte[] buf=new Byte[10];//count is the number of data read: 1~10>0, if 1 to end of file int Count;while ((Count=in.read (BUF))!=-1) {<span style= "white-space:pre" ></span>//Traverse file System.out.println (Tohexstring (BUF));} In.close ();}
<span style= "White-space:pre" ></span>//displays the contents of the file in 16 binary form, showing only the latter 16 bits of private static String tohexstring (byte[] ary) {StringBuilder buf=new StringBuilder (); for (int i=0;i<ary.length;i++) {byte B=ary[i];<span style= " White-space:pre "></span>//get a byte of content int a=b & 0xff;<span style=" White-space:pre "></span>// Use the mask operation to remove the high 24 bit string hex=integer.tohexstring (a); <span style= "White-space:pre" ></span>// Convert it to 16 binary buf.append (hex). Append (""); return buf.tostring ();} public static void Readdemo () throws Ioexception{inputstream in=new FileInputStream ("Demo.txt"); <span style= " White-space:pre "></span>//input stream Open File//read a byte of file, unsigned number filled to the lower eight bits of int//0x000000ff~0x00000000//if read to end of file, return -1// Iterate over a file output int b;while ((B=in.read ())!=-1) {System.out.println (b);} In.close (); <span style= "White-space:pre" ></span>//close File} 
 output stream instance 
public static void Main (string[] args) throws Ioexception{writedemo (); private static void Writedemo () throws Ioexception{outputstream out=new FileOutputStream ("test.txt"); <span style= " White-space:pre "></span>//open file with output stream//write out a low eight-bit out.write of int,//aout.write (66);//Kanji (gbk/ GB2312) Encoding Method Out.write (0XBD); Out.write (0XD3); Out.write (0xd6) out.write (0xd0); Out.write (0XBF); Out.write (0XDA);// Write a byte//write overloaded form byte[] buf={98,99, (byte) 0xd6, (byte) 0xd0};out.write (BUF); <span style= "White-space:pre" > </span>//writes the contents of the BUF to the file Out.write (buf, 2, 2); <span style= "White-space:pre" ></span>//writes a part of an array to the file , buf start from the 2nd position to write two//according to GBK code will try to encode, and then write to Buf out.write ("Try It". GetBytes ("GBK"); <span style= "White-space:pre" > </span>//will "try it" to write to the file in GBK encoding Out.close ();}

Copy a File instance

public static void copy (String src,string DST) throws Ioexception{inputstream in=new FileInputStream (src); <span style = "White-space:pre" ></span>//the original file is the input stream outputstream out=new FileOutputStream (DST); <span style= " White-space:pre "></span>//destination file is output stream byte[] buf=new byte[1024];int c;while ((C=in.read (BUF))!=-1) {<span Style= "White-space:pre" ></span>//one-time reading of 1024 byteout.write (buf,0,c); <span style= "White-space:pre" > </span>//last time may be dissatisfied, so write insurance}in.close (); <span style= "White-space:pre" ></span>//close file Out.close ();}

<span style= "White-space:pre" ></span>//bufferedinputstream,bufferedoutputstream will improve the efficiency of reading, But it's not that all read and write operations have to use this public static void main (string[] args) throws ioexception{//open a stream with input buffering, and when reading the data in the stream, the BIS reads chunks of data into the memory array. Then read it out Bufferedinputstream in=new bufferedinputstream (New FileInputStream ("Demo.txt")); int b=in.read (); <span Style= "White-space:pre" ></span>//b is read by Segment, the first byteSystem.out.println (b) of each paragraph; in.close ();//Create a stream with an output cache, The bufferedoutputstream can provide output buffer management for any stream, and the written data is buffered into the Bufferedoutputstream byte array//After the buffer is full. A one-time write to the target stream inside Bufferedoutputstream out=<span style= "White-space:pre" ></span>//here directly write OutputStream, The following two are the subclass new Bufferedoutputstream (New FileOutputStream ("Test2.txt")), Out.write (0x41);//write to the cache Out.flush ();// Force a buffer in the stream to write Out.close ();//close a stream and force the contents of the buffer to be written out, by default flush} when the stream is closed





Java Learning Notes (15)

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.