首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java中的读文件,文件的创建,写文件

Java中的读文件,文件的创建,写文件

作者头像
达达前端
发布2019-07-03 12:33:55
1.8K0
发布2019-07-03 12:33:55
举报
文章被收录于专栏:达达前端达达前端

前言

大家好,我是 Vic,今天给大家带来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知识点,有兴趣可以继续关注
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.04.23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
    • 读文件
      • 文件的创建
        • 写文件
          • 获取文件的属性
            • 相关知识与技术
              • Java中流的分类
                • 总结
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档