java中File文件操作以及字节流和字符流

1.创建文件类与应用
在导入java.io.File后可以用以下方式创建一个Flie类的对象,只有当文件被实例化后才能对其进行各种操作.

 File file = new File("D:" + File.separator + "a" + File.separator + "hello.txt");
 //separator是File的一个静态属性表示分隔符,用于排除不同操作系统分隔符不同
              
  Path path1 = Paths.get("D:","test","a");//java.nio.file.Path   java.nio.file.Paths
       //Paths辅助类;用于创建Path
  File file = path1.toFile();

在完成对象创建之后,就可以对其进行操作了,可以凭借路径创建一个文件,还有用isFile()判断是否为文件.下面为几个常用操作
1.exists()判断是否存在
2.createNewFile()创建文件并返回Boolean值说明是否创建成功
3.getParentFile()当想要创建的文件在一个不存在的目录时,想要创建文件还需找到它的上级目录,并创建
4.isDirectory()是否为目录,isFile()是否为文件
5. new Date(file.lastModified())最后一次修改时间 需要date获取时间
6. length()返回文件大小

  public static void code1() {
        File file = new File("D:" + File.separator + "a" + File.separator + "hello.txt");
        if (!file.exists()) {
            File parentfile = file.getParentFile();//找到父类目录a
            if (parentfile.exists()) {
                if (parentfile.mkdirs()) {//创建目录以及上级目录
                    System.out.println("Success");
                }
            }
            try {
                if (file.createNewFile()) {
                    System.out.println("Success");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
 public static void code2() {
        File file = new File("D:" + File.separator + "a" + File.separator + "hello.txt");
        file.isDirectory();//是否是目录
        file.isFile();//是否是文件
        new Date(file.lastModified());//修改时间 需要date获取时间
        file.length();//文件大小 目录时不可用
    }
public static void code3() {
        File file = new File("D:" + File.separator + "a" + File.separator + "hello.txt");
        //对目录操作
        // file.list();//返回路径
        File[] files = file.listFiles();//返回目录下文件实例化对象,有几个就是几个数组,当时file是文件时会返回null
        if (files != null) {
            file.getName();//返回文件名
            file.getAbsolutePath();//返回绝对路径
        }
    }

2.字节流
字节流中含有两个大类,InputStream和OutputStream,有关文件的输入输出流继承于此.

 public static void code1() throws IOException {
        //输入流
        //1.1 准备文件
        //1.2 实例化input对象
        //1.3 read()读
        //1.4 业务处理
        //1.5 关闭输入流--finally

        //输出流
        //1.1 准备文件,不存在会自动创建但是目录不行
        //1.2 实例化output对象
        //1.3 write()写
        //1.4 业务处理
        //1.5 关闭流--finally
        //input.txt->output.txt
        File srcFile = Paths.get("D:","Test","input.txt").toFile();
        File outPutFile = Paths.get("D:","Test","outPutFile.txt").toFile();
        FileInputStream ins = new FileInputStream(srcFile);
        FileOutputStream out = new FileOutputStream(outPutFile,true);//append默认false此时不增加文件内容
        //true时每次调用会增加相同内容
        int value = -1;
        while((value= ins.read())!=-1){//结尾返回-1
            value = value+32;
            out.write(value);
        }
        out.flush();//write要写的太多时,刷新到磁盘
        ins.close();
        out.close();//关闭数据流
    }

根据write和read方法提供了不同的读写方式

public static void code2(){
  File file = Paths.get("D:","Test","java.txt").toFile();
      OutputStream out =null;
      out = new FileOutputStream(file);
      out.write(65);

      byte[] data = new byte[]{65,66,67};
      out.write(data);
      out.write(data,2,1);//写入一部分
      String msg = "java6 666";
        out.write('\n');
      out.write(msg.getBytes());
      out.close();
} 

在进行流操作时要注意流的关闭,如果不进行流关闭可能会因为一部分数据还写在缓冲区导致输出文件不完整,java1.7之后提供了AutoCloseable自动关闭流.

public static void copy(String srcFilePath,String destFilePath){
        //参数校验
        if(srcFilePath == null||srcFilePath.isEmpty()){
            throw new IllegalArgumentException("srcFilePath nust be not null/empty");
        }

        if(destFilePath == null||destFilePath.isEmpty()){
            throw new IllegalArgumentException("srcFilePath nust be not null/empty");
        }
        File srcFile = Paths.get(srcFilePath).toFile();
        File destFile = Paths.get(destFilePath).toFile();
        //文件校验
        if(!srcFile.exists()||!srcFile.isFile()){
            throw new IllegalArgumentException("srcFile nothing");
        }
        File parentFile = destFile.getParentFile();//输出流只会创造文件,所以要准备目录
        if(!parentFile.exists()){
            if(!parentFile.mkdirs()){
                throw new RuntimeException("can not get Path");
            }
        }
        //文件复制
        try(FileInputStream in = new FileInputStream(srcFile);//放入try快自动完成关闭流
            FileOutputStream out = new FileOutputStream(destFile)
        ){
            byte[] buff = new byte[1024];//1k 2k 4k, 8k
            int len =-1;
            while((len = in.read(buff))!=-1){//结束时read()返回-1
                out.write(buff,0,len);//要写偏移量,不然会输出整个数组的值造成数据错误
            }
        }catch (IOException e){
            System.out.println(e.getMessage());
        }
    }

3.字符流
字符流有两大类组成,Write和Read,字符流可以读写由字节流无法完成的字符,如中文这一类语言,同时通过 OutputStreamWriter类建立了字符流和字节流之间的关系

public static void read(){
    File file = Paths.get("D:","Test","java6.txt").toFile();
    try(Reader reader = new FileReader(file)){
        // System.out.println(reader.read());//读入一个字符,返回int,Ascll码
        char[] buffer = new char[10];
        int len = -1;
        while((len = reader.read(buffer))!=-1){
            System.out.print(new String(buffer,0,len));//不用println,这样才能打印出源内容
        }
    }catch(IOException e){
        System.out.println(e.getMessage());
    }
}
public static void byteToChar(){
    File file =Paths.get("D:","Test","outputstreamwriter.txt").toFile();
    try(FileOutputStream out = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(out)//字符流转换
    ){
        //通过字节流构造字符流要注意编码格式
        writer.write("HelloWorld");
        writer.write("科技");

    }catch(IOException e){
        System.out.println(e.getMessage());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值