• 【练习】Java中的读文件,文件的创建,写文件


    前言

    大家好,给大家带来Java中的读文件,文件的创建,写文件的概述,希望你们喜欢

    示意图

    读文件

    public static void read(String path,String filename){
     try{
      int length=0;
      String str="";
      byte buffer[] = new byte[10];
      FileInputStream fis = new FileInputStream(new File(path,filename));
      while((length=fis.read(buffer,0,buffer.length))!=-1){
      str+=new String(buffer,0,length);
      }
      System.out.println(str);
      fis.close();
      }catch(FileNotFoundException e){
       System.out.println("文件不存在");
       }catch(IOException e){
        e.printStackTrace();
      }
    }
    

    文件的创建

    public class FileDemo{
     public static void createFolder(String path){
      File folder=new File(path);
      if(folder.exists()){
       System.out.println("文件夹已存在!");
      }else{
       folder.mkdir();
      }
     }
      public static void createFile(String path,String filename){
      File file=new File(path,filename);
      if(file.exists()){
       System.out.println("文件已存在!");
       System.out.println(file.length());
       }else{
        try{
         file.createNewFile();
        }catch(IOException e){
         System.out.println("文件创建失败");
        }
      }
     }
      public static void main(String[] args){
       FileDemo.createFolder("c:/text");
       FileDemo.createFile("c:/text","1.txt");
      }
    }
    

    写文件

    public static void write(String path,String filename){
     try{
      String str="123456789";
      byte b[] = str.getBytes();
      FileOutputStream fos=new FileOutputStream(new File(path,filename));
      fos.write(b);
      }catch(FileNotFoundException e){
       System.out.println("文件不存在");
      }catch(IOException e){
       System.out.println("写文件失败");
      }
    }
    

    获取文件的属性

    String getName()

    boolean canRead()
    boolean canWrite()

    boolean exits()

    boolean isFile()
    boolean isDirectory()
    boolean isHidden()

    相关知识与技术

    boolean mkdir():创建目录,若成功返回true

    boolean createNewFile():创建一个文件

    boolean delete():删除一个文件

    Java中流的分类

    • 流的运动方向:分为输入流和输出流两种
    • 流的数据类型:分为字节流和字符流

    所有的输入流类都是抽象类,所有的输出流类都是抽象类。

    字节:InputStream,OutputStream
    字符:Reader类,Writer类

    从输入流读取数据:

    FileInputStream vFile=new FileInputStream("File1.dat");
    vFile.read();
    vFile.close();
    

    输出流:

    FileOutputStream oFile=new FileOutputStream("File2.dat");
    oFile.write(vFile.read()):
    oFile.close();
    

    如果觉得不错,那就点个赞吧!❤️

    总结

    • 本文讲了Java中的读文件,文件的创建,写文件,如果您还有更好地理解,欢迎沟通
    • 定位:分享 Android&Java知识点,有兴趣可以继续关注
  • 相关阅读:
    js 创建函数,传递三个参数,返回最大值
    JS 实现 计算1~任意数字之间的所有整数阶乘的和
    npm install
    如何在浏览器上安装 VueDevtools工具
    前端日历插件
    css隐藏元素的几种方法
    less和sass的区别
    vue.js 自定义事件
    vue简单的导航栏
    用jetty启动idea中的maven项目报错Caused by: java.lang.ClassNotFoundException: org.apache.jasper.runtime.JspApplicationContextImpl
  • 原文地址:https://www.cnblogs.com/dashucoding/p/9271602.html
Copyright © 2020-2023  润新知