File类和字节流、字符流的操作

在Java.io包中,File类是唯一一个与文件本身操作有关的类

File类的使用

File类可直接产生实例化对象,需要用到两个构造方法

public File(String pathname) ;
public File(String parent, String child),设置父路径和子路径。

有关文件的方法

//创建一个新文件
public boolean createNewFile() throws IOException
//判断文件是否存在
public boolean exists()
//删除文件
public boolean delete()

举例说明

public class Demo {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Administrator\\Downloads\\file");
        if(file.exists()){
            file.delete();//文件存在则删除
        }else {
            file.createNewFile();//不存在创建
        }
    }
}

但是以上代码有以下问题

  • 针对不同的操作系统,路径分割符不同,Windows下使用"",而Unix下使用的是"/",所以File类定义了一个常量"public static final String separator"来描述
// separator由不同操作系统下的JVM来决定到底是哪个杠杠! File file = new File(File.separator + "Users" + File.separator + "yuisama" + File.separator + "Desktop" + File.separator + "TestIO.java");

目录操作

有关目录的方法:

//取得父路经
public String getParent()
//取得父File对象
public File getParentFile()
//创建目录(无论有多少级父目录,都会创建)
public boolean mkdirs()

举例:

public class Demo {
    public static void main(String[] args) throws IOException {
        File file = new File("C:" + File.separator + "Users" + File.separator +
                "Administrator" + File.separator + "Downloads" +
                File.separator + "file.txt");
        System.out.println(file.getParentFile());
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        if(file.exists()){
            file.delete();
            System.out.println("fail");
        }
        else{
            file.createNewFile();
            System.out.println("succeed");
        }
    }
}

文件信息

File类提供的取得文件信息的方法:

1. 判断路径是否是文件: public boolean isFile()
2. 判断路径是否是目录: public boolean isDirectory()
3. 取得文件大小(字节): public long length()
4. 最后一次修改日期 : public long lastModified()

举例:

public class Demo {
    public static void main(String[] args) throws IOException {
        File file = new File("C:" + File.separator + "Users" + File.separator +
                "Administrator" + File.separator + "Downloads" +
                File.separator + "file.txt");
        System.out.println(file.getParentFile());
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        if(file.exists()){
            System.out.println(file.length());
            System.out.println(file.isDirectory());
        }

    }
}

输出:
在这里插入图片描述

流操作

File类不支持文件内容处理,若要对文件进行处理,就必须通过流来处理,流分为输入流和输出流
在Java.io包中,流分为两种:字节流、字符流
字节流与字符流操作的本质区别只有一个:字节流是原生的操作,而字符流是经过处理后的操作
不管使用的是字节流还是字符流,其基本的操作流程几乎是一样的,以文件操作为例
对于IO操作属于资源处理,所有的资源处理操作(IO操作,数据库操作,网络),最终都要进行关闭

字节输出流

若要通过程序将内容输出,则可以使用输出流
Output Stream类的定义

public abstract class OutputStream implements Closeable, Flushable
Closeable, Flushable这两个接口中的方法:
1. Closeable: public void close() throws IOException;
2. Flushable: public void flush() throws IOException;
OutputStream类中的其他方法
1. 将给定的字节数组内容全部输出:public void write(byte b[]) throws IOException
2. 将部分字节数组内容输出:public void write(byte b[], int off, int len) throws IOException
3. 输出单个字节:public abstract void write(int b) throws IOException;

Output Stream是一个抽象类,若想要实例化,需借助FileOutputStream类,这个类的构造方法

1. 接收File类(覆盖):public FileOutputStream(File file) throws FileNotFoundException
2. 接收File类(追加):public FileOutputStream(File file, boolean append)

举例:

public class FileContentOutput {
    public static void main(String[] args) throws IOException {
        File file = new File("C:" + File.separator + "Users" + File.separator +
                "Administrator" + File.separator + "Downloads" +
                File.separator + "hello.txt");
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        //OutputStream是抽象类,需通过子类进行实例化
        OutputStream out = new FileOutputStream(file);
        String msg = "hello world !";
       //将msg变为Byte数组,写到hello.txt中
        out.write(msg.getBytes());
        //关闭输出流
        out.close();
    }
}

在进行文件输出的时候,所有的文件会自动帮助用户创建,不在需要调用createNewFile()方法手工创建。
我们如果将上述程序重复执行,并不会一直在原有的内容上追加,而是,覆盖,若要进行追加,请看以下代码

public class FileContentOutput {
    public static void main(String[] args) throws IOException {
        File file = new File("C:" + File.separator + "Users" + File.separator +
                "Administrator" + File.separator + "Downloads" +
                File.separator + "hello.txt");
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        OutputStream out = new FileOutputStream(file,true);//只是在这块加了true,其他地方均没有做更改
        String msg = "hello world !";
        out.write(msg.getBytes());
        out.close();
    }
}

我们若要进行部分内容的输出:
在上述代码中对下行代码做更改

out.write(msg.getBytes(),0,5);//0表示从那个索引开始,5表示长度

字节输入流

上面利用OutputStream实现从终端输出内容到文件,下面用InputStream类读取文件中的内容
InputStream类的定义:

public abstract class InputStream implements Closeable

在InputStream类提供以下方法

1.读取数据到字节数组中,返回数据的读取个数,若没有数据了还在读,返回-1:public int read(byte b[]) throws IOException.最常用方法
2.读取部分数据到字节数组中,每次只读取传递数组的部分内容,返回读取数据的长度,若没有数据了还在读,返回-1:public int read(byte b[], int off,int len) throws IOException
3. 读取单个字节,每次读取一个字节的内容,直到没有数据了返回-1:public abstract int read() throws
IOException;

同Output Stream一样,要对Input Stream进行实例化需要用到FileInput Stream
文件信息的读取

public class readContent {
    public static void main(String[] args) throws IOException {
        File file = new File("C:" + File.separator + "Users" + File.separator +
                "Administrator" + File.separator + "Downloads" +
                File.separator + "hello.txt");
        if (file.exists()){
            InputStream input = new FileInputStream(file);
            每次可以读取的最大数量
            byte[] data = new byte[1024];
            //读取内容到数组中
            int len = input.read(data);
           //将字节数组转为String
            String msg = new String(data,0,len);
            System.out.println(msg);
        }
    }
}

字符输出流

字符适合处理中文,Writer是字符输出流的处理类,类的定义:

//比Output Stream多了个Appendable j接口
public abstract class Writer implements Appendable, Closeable, Flushable

在Writer类里也提供了write方法,而且该方法接收的类型是char类型,注意:该方法可以直接输出字符串

public void write(String str) throws IOException

通过write输出:

public class writeContent {
    public static void main(String[] args) throws IOException {
        File file = new File("C:" + File.separator + "Users" + File.separator +
                "Administrator" + File.separator + "Downloads" +
                File.separator + "hello.txt");
        if(file.exists()){
            String msg = "hello world";
            Writer out = new FileWriter(file);
            //此时的write中传的是字符串,而OutPut Stream中的write传的是字符数组
            out.write(msg);
            out.close();
        }
    }
}

字符输出流

Reader依然也是一个抽象类。如果要进行文件读取,同样的,使用FileReader
Reader类中没有可以直接读取字符串类型的方法,只能通过字符数组进行读取

public class readContentUseReader {
    public static void main(String[] args) throws IOException {
        File file = new File("C:" + File.separator + "Users" + File.separator +
                "Administrator" + File.separator + "Downloads" +
                File.separator + "hello.txt");
        if(file.exists()){
            Reader input = new FileReader(file);
            char[] chars = new char[1024];
            //读取内容到字符数组中
            int len = input.read(chars);
            String s = new String(chars,0,len);
            System.out.println(s);
        }
    }
}

字符流适合处理中文,字节流适合处理所有数据类型(对中文支持不好)

字节流VS字符流

除了处理中文的情况都优先考虑字节流,因为所有的字符都需要通过内存缓存来进行处理,左右字符流的操作,数据都先保存在缓存中
如果字符流不关闭,数据就有可能保存在缓存中并没有输出到目标源,这汇总情况就必须强制刷新才能得到完整的数据

out.flush(); // 写上此语句表示强制清空缓冲内容,所有内容都输出。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值