Java Advanced-io Stream (2)

Source: Internet
Author: User

<2> Here are some of the more advanced IO streams in 7.0.

5.DirectoryStream enumerates the current file according to the given path

1) Files.newdirectorystream (Path, ". *"); the 2nd parameter specifies the file format for the search

/** * List Directory/file * * @author Lean  @date: 2014-9-22   */public class Dirlisting {public static void main (string[] args) {L Istdir ("E:\\zftphonetv");} public static void Listdir (String filedir) {Path path=paths.get (filedir);D irectorystream<path> dirctorystream= null;try {dirctorystream=files.newdirectorystream (Path, ". *"); for (path P:dirctorystream) {System.out.println ( P.getparent () + "\ \" +p.getfilename ());}} catch (IOException e) {e.printstacktrace ();} Finally{if (dirctorystream!=null) {try {dirctorystream.close ();} catch (IOException e) {e.printstacktrace ();}}}}

6. Merging Files

1) write via BufferedWriter loop

/** * Class Union and File * * @author Lean @date: 2014-9-22 */public class Levefilesample {public static void main (string[] args) {Str ing infilePath1 = "c:/users/administrator/desktop/aa.txt"; String inFilePath2 = "C:/users/administrator/desktop/bb.txt"; String Outfilepath = "C:/users/administrator/desktop/cc.txt"; Concenatefile (Outfilepath, infilepath1,infilepath2);} public static void Concenatefile (String outfilepath,string ... filepaths) {bufferedwriter Bufferedwriter=null;try { Bufferedwriter=new BufferedWriter (New FileWriter (Outfilepath)); for (String filepath:filepaths) {FileReader reader=null;try {reader=new FileReader (new File (FilePath)); int readnum=0;char[] Buff=new char[128];while ((readnum= Reader.read (Buff))!=-1) {bufferedwriter.write (buff,0,readnum);} Bufferedwriter.newline (); buff=new char[128];} catch (IOException e) {}finally{if (reader!=null) {reader.close ();}}}} catch (IOException e) {e.printstacktrace ();} Finally{try {if (bufferedwriter!=null) {bufferedwriter.close ();}} catch (IOexception e) {e.printstacktrace ();}}}} 

2) Sequenceinputstream, by enumerating the loops into the stream. The following: writes the merged stream to a new file

/** * Merge Stream * * @author Lean @date: 2014-9-23 */public class Filemerge {public vector<string> filenames=new vector&lt ; String> ();p ublic vector<inputstream> filestreams=new vector<inputstream> ();p ublic static void Main ( String[] args) {filemerge filemerge=new filemerge (); Filemerge.getfilenames (); try {if (Filemerge.getfilestream ()) { Filemerge.mergefiles ();}} catch (FileNotFoundException e) {e.printstacktrace ();}} private void Mergefiles () {String outfilepath= "c:/users/administrator/desktop/kk.txt"; OutputStream outputstream= Null;byte[] Buff=new byte[512];int readnum=0;try {outputstream=new fileoutputstream (OutFilePath); Sequenceinputstream sequenceinputstream=new Sequenceinputstream (filestreams.elements ()); while (readNum= ( Sequenceinputstream.read (Buff))) (!=-1) {outputstream.write (buff,0,readnum);}} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} Finally{if (outputstream!=null) {try {outputstream.close ();} catch (Ioexception e) {e.printstacktrace ();}}}} Private Boolean GetFileStream () throws FileNotFoundException {if (filenames.size () <1) return False;for (String Filename:filenames) {Filestreams.add (new FileInputStream (FileName));} return true;} public void GetFileNames () {String afile= "c:/users/administrator/desktop/a.txt"; String bfile= "C:/users/administrator/desktop/b.txt"; String cfile= "C:/users/administrator/desktop/c.txt"; Filenames.add (Afile); Filenames.add (bFile); Filenames.add ( cFile);}}

7.bytearrayoutputstream/dataoutputstream and Bytearrayinputstream/datainputstream correspond to each other, Data is an adorner of byte. General application in the case of object conversion to byte array transfer, the transmitted object does not need to inherit any interfaces.

/** * Byte stream/Array app * * @author Lean @date: 2014-9-23 */public class Livedata {private Bytearrayoutputstream outputstream;pub Lic static void Main (string[] args) {livedata data=new livedata ();d ata.createdata ();d ata.readdata ();} public void Createdata () {try {outputstream=new bytearrayoutputstream ();D Ataoutputstream dataoutputstream=new DataOutputStream (OutputStream); for (int i = 0; I <20; i++) {Trade trade=new Trade (i);d ataoutputstream.writeint ( Trade.scripcode);d ataoutputstream.write (trade.time);d ataoutputstream.writedouble (trade.bid); Dataoutputstream.writedouble (Trade.offer);d ataoutputstream.writedouble (Trade.high); Dataoutputstream.writedouble (Trade.low);d Ataoutputstream.writelong (trade.quantity);}} catch (IOException e) {e.printstacktrace ();}} public void ReadData () {byte[] timebuff=new byte[8]; Bytearrayinputstream inputstream=new Bytearrayinputstream (Outputstream.tobytearray ());D Atainputstream Datainputstream=new DataInputStream (InputStream); try {for (int i = 0; i <; i++) {int SCRIPcode=datainputstream.readint ();d atainputstream.read (Timebuff); String Time=new string (timebuff);d ouble bid=datainputstream.readdouble ();d ouble offer=datainputstream.readdouble () ;d ouble high=datainputstream.readdouble ();d ouble low=datainputstream.readdouble (); Long quantity= Datainputstream.readlong (); System.out.println ("scripcode>" +scripcode+ "time>" +time+ "bid>" +bid+ "offer>" +offer+ "high>" +high+ " Low> "+low+" quantity> "+quantity+" ");}} catch (IOException e) {e.printstacktrace ();}}}

8. Sometimes, we need to calculate the number of words in a document, or the control of the document into the control of the document content (Control/Query text/number). Java provides us with Streamtokenizer. This class can change the file flow to a command, which is equivalent to the pointer controlling the memory.

/** * Text/number parsing * * @author Lean  @date: 2014-9-23   */public class Wordandnumberparser {public static void main (string[ ] args) {wordandnumberparser parser=new wordandnumberparser ();p arser.parsefile ("c:/users/administrator/desktop/ Kk.txt ");} public void Parsefile (String fileName) {int Wordcount=0;int numbercount=0;try (filereader reader=new FileReader ( FileName);) {streamtokenizer tokenizer=new streamtokenizer (reader); tokenizer.slashslashcomments (true); Tokenizer.slashstarcomments (True); while (Tokenizer.nexttoken ()!=streamtokenizer.tt_eof) {if (tokenizer.ttype== Streamtokenizer.tt_word) {wordcount++;} else if (tokenizer.ttype==streamtokenizer.tt_number) {numbercount++;} if (Tokenizer.sval!=null&&tokenizer.sval.equals ("a")) {System.out.println (tokenizer.tostring ());}} System.out.println ("WordCount:" +wordcount + "  numbercount:" +numbercount);} catch (Exception e) {System.out.println ("error parser");}}}

9.RandomAccessFile is also an operation on a file, except that it is an operation on a byte. The Seek () method skips illegal content. Its general application is in multi-threaded download/breakpoint download. The following is an example of a breakpoint download:

/** * * * @author Lean  @date: 2014-9-23   */public class Recordfile {public static int filelength (String urlpath) {Htt Purlconnection connection=null;int length=0;try {URL url=new url (urlpath); connection= (HttpURLConnection) Url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout ((); Connection.getresponsecode () ==200) {length=connection.getcontentlength ();}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return length;} public static long Downfilelength (String downpath) {file File=new file (Downpath); return File.length ();}}

/** * * * @author Lean @date: 2014-9-23 */public class Breakpointdownload extends Thread{private String downloadpath;pri Vate string Urlpath;public breakpointdownload (String downloadpath,string urlpath) {this.downloadpath=downloadpath; This.urlpath=urlpath;} @Overridepublic void Run () {randomaccessfile raf=null;inputstream fis=null; HttpURLConnection conn=null;try {int allfilelength=recordfile.filelength (urlpath); Long currdownlength= Recordfile.downfilelength (Downloadpath); long startindex=currdownlength!=0?currdownlength+1:currdownlength; System.out.println (allfilelength+ "" +currdownlength); conn= (httpurlconnection) New URL (URLPath). OpenConnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout,//request header note!conn.setrequestproperty ("Range", "Bytes=" +startindex+ "-" +allfilelength); if (Conn.getresponsecode () ==206) {raf=new randomaccessfile (DownLoadPath, " RWD "); Raf.seek (StartIndex); Fis=conn.getinputstream (); byte[] Buff=new byte[512];int readnum=0;while ((readnum= ( Fis.read (bUFF))) (!=-1) {raf.write (buff,0,readnum);}}} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} Finally{try {if (raf!=null) {raf.close ();} if (fis!=null) {fis.close ();} Conn.disconnect ();} catch (IOException e) {e.printstacktrace ();}}}}

(The high-level part is also like Printstream,linenumberinputstream,pushbackinputstream, but less use)

Java Advanced-io Stream (2)

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.