JAVA io 包小結

來源:互聯網
上載者:User

標籤:磁碟   with   otf   標準輸入   nps   rgs   pst   wro   can   

IO 無非讀寫 I --》 Reader 

       O--> Writer

為了方便字元 或者 文字檔的 操作創造出了 字元流

尤其是 緩衝字元輸入輸出資料流(BufferedReader,BufferedWriter)   readLine 的方法 簡直太好用了

而底層還是用的 位元組流

尤其是 緩衝位元組輸入輸出資料流(BufferedInputStream,BufferedOutput)   read(字元數組,offset,len) 的方法 簡直太好用了

/**
* I/O 流:I->Input O->Output
* I/O流:用於不同裝置之間進行資料轉送
* 用java書寫代碼進行的I/O傳輸
* I/O在java中的體現:存在一個體系:封裝在了IO包裡面
* 資料轉送分為:
* 位元組流(資料以位元組的形式進行傳輸):
*
* 字元流(資料以位元組的形式進行傳輸):
* 都是操作檔案,文本以字元為主,創造出了字元流
*
* ascII(老美) A - 65 a - 97
*
* 漢字:GB2312編碼錶(存放了幾千個漢字)
* 漢字:GBK編碼錶(收納了幾萬個漢字)
* 漢字:18030編碼錶(56個名族)
*
* 國際碼錶:utf-8(unicode)
*
* 字元流是基於位元組流:只所以要使用字元流:方便
*
* IO包:有四個基類
* 位元組流基類:InputStream,OutputStream
* 字元流基類:Reader,Writer
*
* 會有很多子類:FileInputStream
* (以當前基類名字為尾碼,前面的名字代碼的是具體的操作對象)
* FileReader
* (以當前基類名字為尾碼,前面的名字代碼的是具體的操作對象)
*/
/**
* IO流: new FileWriter(fileName);這個構造方法:
* 假如該檔案存在於目前的目錄下,則建立一個該名字的檔案,
* 並且把之前那個檔案覆蓋掉 不論如何,都會建立一個檔案
* 在調用該構造方法的時候:如果指定路徑不存在,則會產生FileNotFoundExeception
*/
/* 把握四個基類, InputStreamReader = InputStream + Reader 也就是說具體操作對象是 InputStream 而操作後的的對象是 Reader
簡單易理解的方式:位元組流是低級流,字元流進階流,進階流是基於低級流的基礎的,為了讀取更方便,字元轉位元組是電腦只認識低級流
因為電腦底層只識別二進位0 1

OutputStreamWriter和InputStreamReader

在整個IO包中,實際上就是分為位元組流和字元流,但是除了這兩個流之外,還存在了一組位元組流-字元流的轉換類。

OutputStreamWriter:是Writer的子類,將輸出的字元流變為位元組流,即:將一個字元流的輸出對象變成位元組流的輸出對象。

InputStreamReader:是Reader的子類,將輸入的位元組流變為字元流,即:將一個位元組流的輸入對象變成字元流的輸入對象。

一般在操作輸入輸出內容就需要使用位元組或字元流,但是有些時候需要將字元流變成位元組流的形式,或者將位元組流變為字元流的形式,所以,就需要另外一群組轉換流的操作類。

FileWriter和FileReader的說明

從JDK文檔中可以 知道FileOutputStream是OutputStream的直接子類。FileInputStream也是InputStream的直接子類,但 是在字元流檔案的兩個操作類卻有一些特殊,
FileWriter並不直接是Writer的子類,而是OutputStreamWriter的子類,而 FileReader也不直接是Reader的子類,而是InputStreamReader的子類,
那麼從這兩個類的繼承關係就可以清楚的發現,不管是 使用位元組流還是字元流實際上最終都是以位元組的形式操作輸入輸出資料流的。
也就是說,傳輸或者從檔案中讀取資料的時候,檔案裡真正儲存的資料永遠是位元組。
*/

/*讀取鍵盤輸入的 三種形式 */import java.io.*;import java.util.*;import java.util.Scanner;class MyTest{public static void main(String [] args) throws Exception{//方法一Scanner scanner =new Scanner(System.in);String inputStr=scanner.nextLine();System.out.println(inputStr);//方法二BufferedReader bufreader=new BufferedReader(new InputStreamReader(System.in));String line=null;while((line=bufreader.readLine())!=null){System.out.println(line);}}}/* 把疊詞 簡化 */class  AbrreviateDemo{public static void main(String [] args){String str="II...LLL...ove..ee.....you!";String regex="\\.+";String replaceStr="";str=retriveStr(str,regex,replaceStr);regex="(.)\\1+";replaceStr="$1";str=retriveStr(str,regex,replaceStr);System.out.println(str);}public static String retriveStr(String str,String regex,String replaceStr){return str.replaceAll(regex,replaceStr);}}/* 將一堆雜亂的 IP 位址進行排序 */import java.util.*;class SortIP{public static void main(String [] args){String IP="192.168.0.5 2.2.3.4 127.0.0.1";printAfterSort(IP);}public static void printAfterSort(String str){String regex="(0*\\d+)";str=str.replaceAll(regex,"00$1");regex="0*(\\d{3})";str=str.replaceAll(regex,"$1");System.out.println(str);regex=" +";String [] strArray=str.split(regex);Arrays.sort(strArray);for(int i=0;i<strArray.length;i++){System.out.println(strArray[i].replaceAll("0*(\\d+)","$1"));}//System.out.println(str); }}/* 郵箱地址校正 */class checkMailDemo{public static void main(String [] args){String str="[email protected]";System.out.println("result: "+checkMail(str));//String regex="";}public static boolean checkMail(String str){String regex="[a-zA-Z0-9_]+[@][a-zA-Z0-9]+(\\.[a-zA-Z]+){1,3}";regex="\\[email protected]\\w+(\\.\\w+){1,3}";return str.matches(regex);}}/* 從一堆雜亂的字串中擷取需要的手機號碼 */import java.util.regex.*;class RegexDemo{public static void main(String [] args){String str="1afasdf13874057617weojfjlj";String regex="[1-9][3,5,8]\\d{9}";retriveStr(str,regex);}public static void retriveStr(String str,String regex){Pattern p=Pattern.compile(regex);Matcher m=p.matcher(str);while(m.find()){String tempstr=m.group();System.out.println(tempstr);}}}/* 讀取鍵盤標準輸入資料流並大寫方式列印到控制台 */import java.io.*;import java.util.*;class UpercaseSystemIn{public static void main(String [] args) throws IOException{InputStream in=System.in;doUpcaseReadIn(in);}public static void doUpcaseReadIn(InputStream in) throws IOException{BufferedReader bufr=new BufferedReader(new InputStreamReader(in));String str=null;while((str=bufr.readLine())!=null){System.out.println(str.toUpperCase());if(str.equalsIgnoreCase("exit")) System.exit(0);  //break }}}/* 讀取某個貼吧郵箱地址並列印到控制台 注意這裡的正則*/import java.net.*;import java.io.*;import java.util.*;import java.util.regex.*;class SpiderTest{public static void main(String [] args) throws Exception{URL url=new URL("http://tieba.baidu.com/p/2314539885");getEmailAddressFromURL(url);}public static void getEmailAddressFromURL(URL url) throws Exception{URLConnection urlconn=url.openConnection();BufferedReader bufreader = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));String line=null;String regex="\\[email protected]\\w+(\\.\\w+)+";Pattern p=Pattern.compile(regex);while ((line=bufreader.readLine())!=null){Matcher m = p.matcher(line);while(m.find()){System.out.println(m.group());}//System.out.println(line);}}}/* 實現本地二進位檔案拷貝 */import java.io.*;class CopyImg{public static void main(String [] args){BufferedInputStream bufinps=null;BufferedOutputStream bufotps=null;try{bufinps=new BufferedInputStream(new FileInputStream("psb.jpg"));bufotps=new BufferedOutputStream(new FileOutputStream("psb_copy.jpg"));byte [] buf=new byte[8192];int len=0;while((len=bufinps.read(buf))>0){bufotps.write(buf,0,len);//bufotps.flush();}}catch(IOException ioe){ioe.printStackTrace();}finally{if(bufinps!=null)try{bufinps.close();}catch(IOException ioe){ioe.printStackTrace();}if(bufotps!=null)try{bufotps.close();}catch(IOException ioe){ioe.printStackTrace();}}}}/* 從某個網頁爬取符合規則的郵箱地址並儲存到本地磁碟路徑下 */import java.io.*;import java.util.regex.*;import java.net.*;import java.util.*;class Spider{public static void main(String [] args) throws Exception{URL url=new URL("http://tieba.baidu.com/p/2314539885");//String [] emailAddress=ArrayList<String> emailList=getEmailByURL(url);for(String emailAddress:emailList){System.out.println(emailAddress);}String qualifiedName="c://users//ghc//desktop//test//emailAddress.txt";writeEmailToFile(qualifiedName,emailList);}// Read html from urlpublic static ArrayList<String> getEmailByURL(URL url) throws Exception{URLConnection urlconn=url.openConnection();BufferedReader bufreader =new BufferedReader(new InputStreamReader(urlconn.getInputStream()));//regex  match patternString regex="\\[email protected]\\w+(\\.\\w+)+";Pattern p=Pattern.compile(regex);ArrayList<String> emailList=new ArrayList<String>();String line=null;while((line=bufreader.readLine())!=null){Matcher m=p.matcher(line);// Start to iterator the one matches while(m.find()){emailList.add(m.group());//System.out.println(m.group());}//System.out.println(line);}return emailList;}public static void writeEmailToFile(String qualifiedName,ArrayList<String> emailList) throws Exception{BufferedWriter bufwriter=new BufferedWriter(new FileWriter(qualifiedName));for(int i=0;i<emailList.size();i++){bufwriter.write(emailList.get(i));bufwriter.newLine();bufwriter.flush();}}}/* 從某個網頁爬取圖片的 URL 地址然後 進行 下載到本地磁碟路徑 準系統已經實現,但是正則需要自行調整 */import java.net.*;import java.io.*;import java.util.regex.*;import java.util.*;class ImgSpider{public static void main(String [] args){saveImgFromURL("http://image.baidu.com/","c:/users/ghc/desktop/test/");System.gc();}public static boolean downLoadImg(String line,String path){boolean flag=true;FileOutputStream fos=null;BufferedInputStream bufinpts=null;BufferedOutputStream bufopts=null;path=path.replace("<","");/* System.out.println(line);System.out.println(path); */try{bufinpts=new BufferedInputStream((new URL(line)).openConnection().getInputStream());fos=new FileOutputStream(path);bufopts=new BufferedOutputStream(fos);byte [] buf=new byte[1024];int len=-1;while((len=bufinpts.read(buf))!=-1){bufopts.write(buf,0,buf.length);}}catch(IOException ioe){ioe.printStackTrace();flag=false;}finally{if(bufopts!=null)try{bufopts=null;bufopts.close();}catch(IOException ioe){ioe.printStackTrace();}if(fos!=null) try{ fos=null; fos.close(); } catch(IOException ioe){ioe.printStackTrace();} }return flag;}public static boolean saveImgFromURL(String urlStr,String folder){boolean flag=true;URL url=null;//InputStream in=null;String line=null;BufferedReader bufr=null;Pattern p=null;Matcher m=null;ArrayList<String> imgList=null;try{url=new URL(urlStr);URLConnection urlconn=url.openConnection();bufr=new BufferedReader(new InputStreamReader(urlconn.getInputStream()));imgList=new ArrayList<String>();String regex="<img.*src=(.*?)[^>]*?>";p=Pattern.compile(regex);while((line=bufr.readLine())!=null){m=p.matcher(line);while(m.find()){System.out.println(m.group());imgList.add(m.group());}//System.out.println(line);}Iterator<String> it=imgList.iterator();while(it.hasNext()){line=it.next();folder+=line.substring(line.lastIndexOf("/",2) + 1,                          3)+".png";  //http://www.jb51.net/images/logo.gifm=Pattern.compile("http://(\\w+\\.)+[a-z]+/images/(\\w+\\.)+[a-z]{3}").matcher(line);while(m.find()){line=m.group();//System.out.println(line);downLoadImg(line,folder);}}}catch(MalformedURLException mfe){mfe.printStackTrace();flag=false;}catch(IOException ioe){ioe.printStackTrace();flag=false;}finally{if (bufr!=null)try{bufr=null;bufr.close();}catch(IOException ie){ ie.printStackTrace();}}return flag;}}/*正則 小練習 */class Demo{public static void main(String [] args){String qq="1212345";boolean checkResult=checkQQ(qq);System.out.println(checkResult ? qq+" is right": qq+" is wrong!!!");String telnumber="15974097817";checkResult=checkTel(telnumber);System.out.println(checkResult ? telnumber+" is right": telnumber+" is wrong!!!");String path="c:\\users\\frank\\abqqcdkkkefghhijkkkkkl.txt";String regex="(.)\\1+";    //疊詞切割注意引入組的概念,\n 代表引用第幾組 + 出現1次或多次 qq 或者 kkk 均會被當作切割符printAfterSplit(path,regex);System.out.println("=================");regex="\\.";printAfterSplit(path,regex);String str="abcddeffffg";   regex="(.)\\1{3,}";String replaceStr="$1";printAfterReplaceStr(str,regex,replaceStr);}// 以下兩個均是正則匹配 校正字串的函數public static boolean checkTel(String telnumber){String regex="[1][3,5,8]\\d{9}";return telnumber.matches(regex);}public static boolean checkQQ(String qq){//boolean result=false;String regex="[1-9][0-9]{4,14}";   regex="[1-9]\\d{4,14}";return qq.matches(regex);/* int len=qq.length();if(len<5 || len>15 || qq.startsWith("0")){System.out.println("length or startWith issue!!!");//return result;}else {char [] ary=qq.toCharArray();for(int i=0;i<ary.length;i++){if(!(ary[i]>=‘0‘ && ary[i]<=‘9‘)){System.out.println("not between 0 and 9 !!!");break;//return result;}else result=true;}} *///return result;}// 以下兩個均是正則 切割字串的函數public static void printAfterSplit(String path,String regex){String [] ary=path.split(regex);for(String s:ary){System.out.println(s);}}// 以下兩個均是自訂正則替換字串函數public static void printAfterReplaceStr(String str,String regex,String replaceStr){String resultStr=str.replaceAll(regex,replaceStr);System.out.println(resultStr);}}

  

JAVA io 包小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.