Java IO详解(一)------File 类

本文详细介绍Java中的File类,包括其作用、构造方法、常用方法及一些实用技巧。讲解了跨平台路径处理方式,并演示了如何创建、删除文件及目录等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

File 类:文件和目录路径名的抽象表示。

注意:File 类只能操作文件的属性,文件的内容是不能操作的。

 

1、File 类的字段

 

  我们知道,各个平台之间的路径分隔符是不一样的。

  ①、对于UNIX平台,绝对路径名的前缀始终为"/" 。 相对路径名没有前缀。 表示根目录的抽象路径名具有前缀"/"和空名称序列。

  ②、对于Microsoft Windows平台,包含驱动器说明符的路径名的前缀由后面跟着":"的驱动器号组成,如果路径名是绝对的,则可能后跟"\\" 。 UNC路径名的前缀为"\\\\" ; 主机名和共享名称是名称序列中的前两个名称              没有有指定驱动器的相对路径名没有前缀。

  那么为了屏蔽各个平台之间的分隔符差异,我们在构造 File 类的时候(如何构造,请看下面第二点),就可以使用上述 Java 为我们提供的字段。

1
2
System.out.println(File.separator);//输出 \  
        System.out.println(File.pathSeparator);//输出 ;

  那么我们可以看出:

    File.pathSeparator指的是分隔连续多个路径字符串的分隔符

    File.separator是用来分隔同一个路径字符串中的目录的

 

 

2、File 类的构造方法

如何使用上述构造方法,请看如下例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//不使用 Java 提供的分隔符字段,注意:这样写只能在 Windows 平台有效
        File f1 = new File("D:\\IO\\a.txt");
        //使用 Java 提供的分隔符
        File f2 = new File("D:"+File.separator+"IO"+File.separator+"a.txt");
        System.out.println(f1);//输出 D:\IO\a.txt  
        System.out.println(f2);//输出 D:\IO\a.txt
         
        //File(File parent, String child)
        //从父抽象路径名和子路径名字符串创建新的 File实例。
        File f3 = new File("D:");
        File f4 = new File(f3,"IO");
        System.out.println(f4); //D:\IO
         
        //File(String pathname)
        //通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
        File f5 = new File("D:"+File.separator+"IO"+File.separator+"a.txt");
        System.out.println(f5); //D:\IO\a.txt
         
        //File(String parent, String child)
        //从父路径名字符串和子路径名字符串创建新的 File实例。
        File f6 = new File("D:","IO\\a.txt");
        System.out.println(f6); //D:\IO\a.txt

  

 

3、File 类的常用方法

  ①、创建方法

    1.boolean createNewFile() 不存在返回true 存在返回false
    2.boolean mkdir() 创建目录,如果上一级目录不存在,则会创建失败
    3.boolean mkdirs() 创建多级目录,如果上一级目录不存在也会自动创建

 

  ②、删除方法

    1.boolean delete() 删除文件或目录,如果表示目录,则目录下必须为空才能删除
    2.boolean deleteOnExit() 文件使用完成后删除

 

  ③、判断方法

    1.boolean canExecute()判断文件是否可执行
    2.boolean canRead()判断文件是否可读
    3.boolean canWrite() 判断文件是否可写
    4.boolean exists() 判断文件或目录是否存在
    5.boolean isDirectory()  判断此路径是否为一个目录
    6.boolean isFile()  判断是否为一个文件
    7.boolean isHidden()  判断是否为隐藏文件
    8.boolean isAbsolute()判断是否是绝对路径 文件不存在也能判断

 

   ④、获取方法

    1.String getName() 获取此路径表示的文件或目录名称
    2.String getPath() 将此路径名转换为路径名字符串
    3.String getAbsolutePath() 返回此抽象路径名的绝对形式
    4.String getParent()//如果没有父目录返回null
    5.long lastModified()//获取最后一次修改的时间
    6.long length() 返回由此抽象路径名表示的文件的长度。
    7.boolean renameTo(File f) 重命名由此抽象路径名表示的文件。
    8.File[] liseRoots()//获取机器盘符
    9.String[] list()  返回一个字符串数组,命名由此抽象路径名表示的目录中的文件和目录。
    10.String[] list(FilenameFilter filter) 返回一个字符串数组,命名由此抽象路径名表示的目录中满足指定过滤器的文件和目录。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//File(File parent, String child)
        //从父抽象路径名和子路径名字符串创建新的 File实例。
        File dir = new File("D:"+File.separator+"IO");
        File file = new File(dir,"a.txt");
         
        //判断dir 是否存在且表示一个目录
        if(!(dir.exists()||dir.isDirectory())){
            //如果 dir 不存在,则创建这个目录
            dir.mkdirs();
            //根据目录和文件名,创建 a.txt文件
            file.createNewFile();
 
        }
        //返回由此抽象路径名表示的文件或目录的名称。 这只是路径名称序列中的最后一个名字。 如果路径名的名称序列为空,则返回空字符串。
        System.out.println(file.getName()); //a.txt
        //返回此抽象路径名的父null的路径名字符串,如果此路径名未命名为父目录,则返回null。
        System.out.println(file.getParent());//D:\IO
        //将此抽象路径名转换为路径名字符串。 结果字符串使用default name-separator character以名称顺序分隔名称。
        System.out.println(file.getPath()); //D:\IO\a.txt

 

 

4、File 的一些技巧

  ①、打印给定目录下的所有文件夹和文件夹里面的内容 

1
2
3
4
5
6
7
8
9
10
11
public static void getFileList(File file){
        //第一级子目录
        File[] files = file.listFiles();
        for(File f:files){
            //打印目录和文件
            System.out.println(f);
            if(f.isDirectory()){
                getFileList(f);
            }
        }
    }

  测试:

1
2
3
4
public static void main(String[] args) throws Exception {
        File f = new File("D:"+File.separator+"WebStormFile");
        getFileList(f);
    }


测试2:

package com.io.action;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;


import sun.org.mozilla.javascript.internal.Undefined;


public class OutputStreamDemo01 {

private static final byte[] Undefined = null;


//读取文件
public static void readToString(String fileName) {  
        String encoding = "gbk";  
        File file = new File(fileName); 
        if(file.exists())
        {
        Long filelength = file.length();  
        byte[] filecontent = new byte[filelength.intValue()];  
        try {  
            FileInputStream in = new FileInputStream(file);  
            in.read(filecontent);  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        //读取所有字符串
        try {  
        System.out.println(new String(filecontent, encoding));
        } catch (UnsupportedEncodingException e) {  
            System.err.println("The OS does not support " + encoding);  
            e.printStackTrace();  
//            return null;  
        }  
      }
    }

//读取文件
public static byte[] readToByte(String fileName) throws UnsupportedEncodingException {  
        String encoding = "gbk";  
        File file = new File(fileName);  
        if(file.exists())
        {
        Long filelength = file.length();  
        byte[] filecontent = new byte[filelength.intValue()];  
        try {  
            FileInputStream in = new FileInputStream(file);  
            in.read(filecontent);  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        return new String(filecontent, encoding).getBytes();
        }else
{
return null;
}
    }  


//创建文件并写入数据流
public static void OutputStreamDemo001() throws IOException {
//创建文件并写入信息
String pathname = "D:\\test"  + File.separator+ "001.txt";
File f1 = new File(pathname);
OutputStream outputStream  = null;
outputStream = new FileOutputStream(f1);
//设置只读
// file.setReadOnly();
//new FileOutputStream(file) 后下面判断为TRUE,否则为FALSE;
// System.out.println(f1.isFile());
//写入字符串
String string = "测试!!!!";
// String string1 = new String(string.getBytes("utf-8"),"utf-8");
byte[] b1 = string.getBytes("utf-8");
String pathname2 = "D:\\test"  + File.separator+ "test.txt";
byte[] b2 = readToByte(pathname2);
readToString(pathname2);
if(f1.canWrite())
{
//两次写入 字符串b1 会出现乱码
if(b2 != null || b2 != Undefined)
{
outputStream.write(b2);
}
if(b1 != null || b1 != Undefined)
{
outputStream.write(b1);
}


outputStream.close();
}
}

/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {
OutputStreamDemo001();
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值