- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- 淺談Java中File文件的創(chuàng )建以及讀寫(xiě)
@Test public void test6() throws IOException { File file1 = new File("C:\\IDEA\\h1.txt"); if(!file1.exists()){//文件不存在 file1.createNewFile(); System.out.println("創(chuàng )建成功"); }else{//文件存在 file1.delete(); System.out.println("刪除成功"); } }
輸出
file.mkdir,不會(huì )幫你創(chuàng )建上層目錄 file.mkdirs,會(huì )幫你創(chuàng )建上層目錄
@Test public void test7(){ //創(chuàng )建文件夾,mkdir,不會(huì )幫你創(chuàng )建上層目錄 File file1 = new File("c:\\IDEA\\io2"); boolean mkdir =file1.mkdir(); if(mkdir){ System.out.println("創(chuàng )建成功1"); } //創(chuàng )建文件夾,mkdirs,會(huì )幫你創(chuàng )建上層目錄 File file2 = new File("c:\\IDEA\\io1\\io3"); boolean mkdirs =file2.mkdirs(); if(mkdirs){ System.out.println("創(chuàng )建成功2"); } }
輸出
@Test public void test8(){ //刪除文件或空文件夾 File file1 = new File("c:\\IDEA\\h1.txt"); file1.delete(); }
//遞歸函數刪除所有文件 private boolean deletedir(File dir){ if (dir.isDirectory()) { File[] files = dir.listFiles(); //遞歸刪除目錄中的子目錄下 for (File f:files) { boolean success = deletedir(f); if (!success) { return false; } } } // 目錄此時(shí)為空,可以刪除 return dir.delete(); } @Test public void test8() { File dir = new File("c:\\IDEA"); System.out.println(deletedir(dir)); }
1.對于文本文件(.txt,.java,.c,.cpp),使用字符流處理
2.對于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt)使用字節流處理
@Test public void test9() { FileReader fr = null;//自動(dòng)補的 try { //1.實(shí)例化File類(lèi)的對象,指明要操作的文件 File file1 = new File("c:\\IDEA\\hello.txt"); file1.createNewFile();//要拋出異常 //2.提供具體的流 fr = new FileReader(file1); //3.數據的讀入 //read():返回讀入的一個(gè)字符,如果達到文件末尾,返回-1 int data = fr.read(); while(data!=-1){ System.out.print((char)data); data = fr.read(); } } catch (IOException e) { e.printStackTrace(); }finally { try { //4.流的關(guān)閉操作 if(fr!=null)//防止沒(méi)有實(shí)例化成功,避免空指針異常 fr.close(); } catch (IOException e) { e.printStackTrace(); } }
要記得關(guān)閉,因為物理連接JVM垃圾回收機制不會(huì )自動(dòng)回收,要手動(dòng)關(guān)閉。
@Test public void test1() { FileReader fr = null; try { //1.File類(lèi)的實(shí)例化 File file = new File("hello.txt"); //2.FileReader流的實(shí)例化 fr = new FileReader(file); //3.讀入的操作 //read(char[] cbuf):返回每次讀入cbuf數組中的字符的個(gè)數。如果達到文件末尾,返回-1 char[] cbuf = new char[5]; int len; while ((len = fr.read(cbuf)) != -1) { //錯誤的寫(xiě)法 //for(int i=0;i<cbuf.length;i++{ // System.out.println(cbuf[i]); /
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站