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

前言

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

719de3f9174ff5de1d29a3a77b53bfba.png

读文件

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知识点,有兴趣可以继续关注

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值