File類概述java
File更應該叫作一個路徑,是一個文件和目錄路徑名的抽象表示形式。api
構造方法ide
package com.learn.io; import java.io.File; import java.io.IOException; public class IoTest { public static void main(String[] args) throws IOException { File file = new File("C:\\Users\\Administrator\\Desktop\\sss.txt"); System.out.println(file.exists()); } }
這種構造方式,parent和child爲變量,更加靈活spa
public static void main(String[] args) throws IOException { String parent="C:\\Users\\Administrator\\Desktop"; String child="sss.txt"; File file = new File(parent,child); System.out.println(file.exists()); }
這種構造方式parent能夠使用file類的一些方法(較String類型更強大)code
public static void main(String[] args) throws IOException { File file1 = new File("C:\\Users\\Administrator\\Desktop"); String child="sss.txt"; File file = new File(file1, child); System.out.println(file.exists()); }
File類的建立方法對象
若文件已存在則建立失敗(或file路徑不正確),返回falseblog
public static void main(String[] args) throws IOException { File file = new File("C:\\Users\\Administrator\\Desktop\\sss.txt"); boolean createNewFile = file.createNewFile(); System.out.println(createNewFile); }
若文件夾已存在則建立失敗(或file路徑不正確),返回falseget
public static void main(String[] args) throws IOException { File file= new File("C:\\Users\\Administrator\\Desktop\\hijiahsi"); boolean mkdir = file.mkdir(); System.out.println(mkdir); }
若是父文件夾不存在,會幫你建立出來string
public static void main(String[] args) throws IOException { File file= new File("C:\\Users\\Administrator\\Desktop\\xuweiwen\\hahaah"); boolean mkdir = file.mkdirs(); System.out.println(mkdir); }
File類的遍歷it
private static void demo7() { File file = new File("C:\\Users\\Administrator\\Desktop"); String[] list = file.list(); for (String name : list) { System.out.println(name); } }
private static void demo8() { File file = new File("C:\\Users\\Administrator\\Desktop"); File[] files = file.listFiles(); for (File childFile : files) { System.out.println(childFile.getName()); } }
獲取桌面上全部以txt結尾的文件(返回true爲放行,false攔截)
public static void main(String[] args) throws IOException { File file = new File("C:\\Users\\Administrator\\Desktop"); String[] list = file.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if(name.endsWith("txt")){ return true; }else{ return false; } } }); for (String string : list) { System.out.println(string); } }
File類的其餘一些api