檔案
1.File物件
java封裝的一個操作檔案及檔案夾(目錄)的物件,可以操作磁盤上的任何一個檔案和檔案夾,
2.創建檔案
方式一:根據路徑構建一個File物件new File(path)
//方式一 @Test public void create01(){ try { String path = URLDecoder.decode("D:\\博客園\\wjj1.txt","UTF-8");//解決中文亂碼,轉UTF-8 File file = new File(path); file.createNewFile(); System.out.println("創建成功01"); } catch (UnsupportedEncodingException e) {//decode方法需要拋例外或捕獲例外 e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
方式二:根據父目錄檔案和子目錄路徑構建一個File物件new File(File,Spath)
//方式二
@Test public void create02(){ String path = null; try { path = URLDecoder.decode("D:\\博客園","UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File parentFile = new File(path);//父目錄檔案 String fileName = "wjj2.txt";//子路徑 File file = new File(parentFile, fileName); try { file.createNewFile(); System.out.println("創建成功02"); } catch (IOException e) { e.printStackTrace(); } }
方式三:根據父目錄路徑和子目錄路徑構建一個File物件new File(Fpath,Spath)
//方式三 @Test public void create03() throws Exception{//拋例外 String path = URLDecoder.decode("D:\\博客園","UTF-8"); String filePath = "wjj3.txt"; File file = new File(path, filePath); file.createNewFile(); System.out.println("創建成功03"); }
運行結果:
3.檔案的相關操作
檔案的路徑相關和判斷功能的構造方法
@Test public void info() throws Exception{ //創建檔案物件 String path = URLDecoder.decode("D:\\博客園\\wjj1.txt","UTF-8"); File file = new File(path); System.out.println("檔案名:"+file.getName()); System.out.println("檔案絕對路徑:"+file.getAbsolutePath()); System.out.println("檔案父目錄:"+file.getParent()); System.out.println("檔案大小(位元組):"+file.length()); System.out.println("檔案是否存在:"+file.exists()); System.out.println("是否是檔案:"+file.isFile()); System.out.println("是否是目錄:"+file.isDirectory()); }
UTF-8一個英文一個位元組,一個漢字三個位元組
運行結果:

檔案洗掉操作的構造方法
@Test public void fileDelete() throws Exception{ String path = URLDecoder.decode("D:\\博客園\\wjj1.txt","UTF-8"); File file = new File(path); if (file.exists()){ if (file.delete()){ System.out.println(path+"洗掉成功"); }else { System.out.println(path+"洗掉失敗"); } }else { System.out.println("檔案不存在"); } }
檔案創建目錄操作的構造方法
@Test public void isMkdir() throws Exception{ String path = URLDecoder.decode("D:\\博客園\\wjj1","UTF-8"); File file = new File(path); if (file.exists()){ System.out.println(path+"該目錄已存在"); }else { if (file.mkdirs()){ System.out.println("創建成功"); }else { System.out.println("創建失敗"); } } }
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528055.html
標籤:其他
上一篇:設計模式---代理模式
下一篇:day11-Servlet01

