1.直接看代码
package File类详解;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws IOException {
//I. 构造方法 三个
// 1. File(String pathName) ★★★ 通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例。
// 2. File(String parent,String child) 根据 parent 路径名字符串和 child 路径名字符串创建一个新 File 实例。
// 3. File(File parent,String child) 根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。
// 注意: 创建一个File对象并没有在磁盘上面创建一个文件(文件夹) ("\"前面都加上一个“\”)
File file = new File("C:\\Users\\甘劭\\Desktop\\enen\\你好\\么么哒.txt"); //(此路径电脑真实存在)
File file1 = new File("G:/Users/AOC/Desktop/","HelloWorld111.txt"); //(此路径电脑不存在)
File file2 = new File(new File("C:\\Users\\甘劭\\Desktop"),"么么哒.txt");
//II. 常用的方法: 注意: 这些方法需要File对象调用:根据File对象中的pathname来操作文件
// 1.创建文件 boolean createNewFile() 如果文件已经存在,返回false;如果文件路径不存在,抛出IO异常
// 2.创建文件夹 boolean mkdir() 如果文件夹已经存在,返回false 如果路径不存在,返回false,没有抛出异常
// boolean mkdirs() 如果路径不存在,会自动先创建路径所需的文件夹
// 3.删除文件和目录 boolean delete() 如果是删除文件夹,必须是空文件夹. 文件就直接删除
// 4. String getName() 得到文件或者目录的名称;
// 5. String getParent() 返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null。
// 6.判断系列方法
// boolean isDirectory() 判断是否是一个目录
// boolean isFile() 判断是否是一个文件
// boolean exists() 测试此抽象路径名表示的文件或目录是否存在
System.out.println(file.exists()); //true
System.out.println(file1.exists()); //false
System.out.println(file.isFile()); //ture
System.out.println(file.isDirectory()); //false
// 7. 注意:listRoots() list() listFile() 的区别
// static File[] listRoots():获取操作系统上的盘符文件对象数组
// File[] listFiles():获取当前文件夹对象下的所有子文件夹和子文件对象(File类型)的数组
// String[] list(): 获取当前文件夹对象下的所有子文件夹和子文件名称(String)的数组
System.out.println(Arrays.toString(file.listRoots())); // [C:\, E:\, F:\]
File file3 = new File("C:\\Users\\甘劭\\Desktop\\enen");
System.out.println(Arrays.toString(file3.list())); //[你好, 我好]
System.out.println(Arrays.toString(file3.listFiles()));
//[C:\Users\甘劭\Desktop\enen\你好, C:\Users\甘劭\Desktop\enen\我好]
// 8.其他方法 和字段
// file.getPath()获取文件对象的抽象路径
// file.getAbsolutePath()获取文件对象的绝对路径
// file.length() ★★★获取文件内的数据的长度
// file.getParentFile() ★★★获取父级文件夹对象
System.out.println(file.getPath()); //C:\Users\甘劭\Desktop\enen\你好\么么哒.txt
System.out.println(file.getAbsolutePath()); //C:\Users\甘劭\Desktop\enen\你好\么么哒.txt
System.out.println(file.length());//获取文件内的数据的长度
File parent = file.getParentFile();//获取父级文件夹对象
System.out.println(parent.getPath()); //C:\Users\甘劭\Desktop\enen\你好
System.out.println(File.pathSeparator);//一种路径分隔符 ,返回的都是字符串类型。 // ";"
System.out.println(File.separator); // "\"
}
}
2. 删除一个文件夹下的所有子文件夹和子文件(子文件夹中的子文件夹和子文件也需要除)
package 删除一个文件夹下的所有子文件夹和子文件;
/*
* 自定义删除文件和文件夹
*/
import java.io.File;
public class Test {
public static void main(String[] args) {
File f = new File("C:\\Users\\甘劭\\Desktop\\enen");
//System.out.println(f.delete());//删除文件夹的时候的看该文件夹内是否为空,空文件夹直接删
deleteAll(f);//删除全部
}
private static void deleteAll(File f) {
if(f !=null && f.exists()){
//判断对象是否为空 和 对象表示的抽象路径下是否真实存在文件
if(f.isFile()||f.listFiles().length ==0){
f.delete();//删除文件
}else{
//表示是个有东西的文件夹
File[] files = f.listFiles();
for (File file : files) {
deleteAll(file);
}
//System.out.println(f.getName()+"文件夹");
f.delete();//删除该有东西()的目录
}
}
}
}
3.统计文件夹下有多少个子文件夹和子文件(子文件夹中的子文件夹和子文件也需要统计)
思路:用文件类型(后缀名不包含 “.”)作为key, 用个数作为value, 放入到map集合中
public class Test {
public static void main(String[] args) {
File f = new File("C:\\Users\\甘劭\\Desktop\\enen");
//map集合,文件类型名--key , 个数--values
Map<String,Integer> map = new HashMap();
getFileTypeCount(f, map); //调用方法获得结果存储在map集合中
//遍历map
Set set = map.entrySet();
for (Object obj : set) {
Entry en = (Entry)obj;
System.out.println( en.getKey()+" "+en.getValue());
}
}
//
public static void getFileTypeCount(File f,Map<String,Integer> map){
File[] files = f.listFiles(); // 获取f目录下的所有文件和文件夹
// 遍历对象数组
for (File file : files) {
if(file.isFile()){
int index = file.getName().lastIndexOf(".");
String str = file.getName().substring(index+1); //获取文件类型。
int nums = map.get(str)==null? 1 : map.get(str)+1; //获取文件个数
map.put(str, nums);
}else if(file.isDirectory()){
getFileTypeCount(file,map); //如果是文件夹 继续递归调用
}
}
}
}
4.自定义文件过滤器
public class Test {
public static void main(String[] args) {
//上传文件 指定一个目标目录 和允许上传的文件类型(只能判断当前目录下,文件夹里面的无从而知)
File file = new File("C:\\Users\\甘劭\\Desktop\\enen");//指定上传的目录
File[] files = upload(file,"html");
if(files.length != 0){
System.out.println("上传成功");
for (File file2 : files) {
System.out.println(file2.getName());
}
}else{
System.out.println("没有符合要求的文件可以上传");
}
}
private static File[] upload(File file, String string) {
ArrayList<File> lists = new ArrayList<>();//允许上传的文件对象保存在该集合内
if(file.isDirectory()){
File[] files = file.listFiles();//获取当前目录下的所有子文件和子文件夹对象
for (File f : files) {
if(f.isFile() && f.getName().endsWith(string)){
lists.add(f);
}
}
}
return lists.toArray(new File[lists.size()]);//将集合转换为对象数组
}
}
5.封装好的 FilenameFilter 和 FileFilter 过滤器接口
FilenameFilter 接口 FileFilter接口
* 接口方法:
* boolean accept(File dir,String name) 可以使用此方法列出指定目录下面的带有某些后缀的文件。
参数:
dir - 被找到的文件所在的目录。
name - 文件的名称。
返回:
当且仅当该名称应该包含在文件列表中时返回 true;否则返回 false。
public class Test implements FilenameFilter {
private String key;//允许上传的文件后缀名称
public Test() {}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public boolean accept(File dir, String name) {
return name.endsWith(key);//判断指定的文件名称的后缀名是不是key,如果是key 添加到文件列表中
}
//进行测试
public static void main(String[] args) {
File file = new File("C:\\Users\\甘劭\\Desktop\\enen");
Test mf = new Test();
mf.setKey("html");//设置能够保存
String[] names = file.list(mf);//传递一个文件过滤器
System.out.println(Arrays.toString(names));
}
}
6. 复制文件夹 (☆☆☆☆☆)
public static void copyFolder(String sourcePath,String targetPath){
try {
(new File(targetPath)).mkdirs();//若没有文件夹就创建一个
File file = new File(sourcePath);
String[] files = file.list();
File temp = null;
for (int i = 0; i < files.length; i++) {
if(sourcePath.endsWith(File.separator)){
temp = new File(sourcePath+files[i]);
}else{
temp = new File(sourcePath+"/"+files[i]);
}
if(temp.isFile()){
FileInputStream fis = new FileInputStream(temp);
FileOutputStream fos = new FileOutputStream(targetPath+"/"+temp.getName().toString());
byte[] b = new byte[1024*5];
int len = -1;
while ((len = fis.read(b))!=-1) {
fos.write(b, 0, len);
}
fos.flush();
fos.close();
fis.close();
}
if(temp.isDirectory()){
copyFolder(sourcePath+"/"+files[i],targetPath+"/"+files[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("复制失败");
}
}
7.Java中获取项目根路径和类加载路径的7种方法
引言
在web项目开发过程中,可能会经常遇到要获取项目根路径的情况,那接下来我就总结一下,java中获取项目根路径的7种方法,主要是通过thisClass和System,线程和request等方法。
(1):this.getClass().getResource("/");
(2):file.getCanonicalPath();
(3):this.getClass().getClassLoader();
(4):System.getProperty("user.dir");
(5):System.getProperty("java.class.path");
(6):Thread.currentThread().getContentClassLoader();
(7):request.getSession().getServletContext();
代码如下:
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**获取项目根路径的方法*/
public class MyUrlDemo {
public static void main(String[] args) {
MyUrlDemo muDemo = new MyUrlDemo();
try {
muDemo.showURL();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showURL() throws IOException {
// 第一种:获取类加载的根路径 D:\git\daotie\daotie\target\classes
File f = new File(this.getClass().getResource("/").getPath());
System.out.println("path1: "+f);
// 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录 D:\git\daotie\daotie\target\classes\my
File f2 = new File(this.getClass().getResource("").getPath());
System.out.println("path1: "+f2);
// 第二种:获取项目路径 D:\git\daotie\daotie
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
System.out.println("path2: "+courseFile);
// 第三种: file:/D:/git/daotie/daotie/target/classes/
URL xmlpath = this.getClass().getClassLoader().getResource("");
System.out.println("path3: "+xmlpath);
// 第四种: D:\git\daotie\daotie
System.out.println("path4:" +System.getProperty("user.dir"));
/*
* 结果: C:\Documents and Settings\Administrator\workspace\projectName
* 获取当前工程路径
*/
// 第五种: 获取所有的类路径 包括jar包的路径
System.out.println("path5: "+System.getProperty("java.class.path").split(";")[0]);
// 第六种: 获取项目路径 D:/git/daotie/daotie.target/classes/
System.out.println("path6: "+Thread.currentThread().getContentClassLoader().getResource("").getPath());
//第七种 表示到项目的根目录下, 要是想到目录下的子文件夹,修改"/"即可
String path7 = request.getSession().getServletContext().getRealPath("/"));
System.out.pringln("path7: "+path7);
}
}