java io例子_java之IO实例

实例1:从键盘接收一个文件夹路径,把文件夹中的所有文件以及文件夹的名字按层级打印

分析:这里用到了file类的方法和递归

public  class  Test10{

public  static  void   main(String[ ]  args)

{

Scanner  sc=new Scanner(System.in);

String  path=sc.nextLine( );

File   f=new  File(path);

System.out.println(f.getName( ));

method(f,1);

}

public  static  void  method(File   f, int  level)

{

File [ ]   files=f.listFiles( );

for(File    file:files)

{

for(int  i=0;i

{

System.out.print("\t");

}

System.out.println(file.getName( ));

if(file.isDirectory ( ))

{

method(file,level+1);

}

}

}

}

实例2:从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中

public class Test9 {

public static void main(String[] args) throws IOException {

Scanner sc = new Scanner(System.in);

System.out.println("请输入来源路径");

String pathSrc = sc.nextLine();

System.out.println("请输入目的地路径");

String pathDest = sc.nextLine();

method(pathSrc,pathDest);

}

public static void method(String pathSrc,String pathDest) throws IOException{

//封装了来源,获取了来源中的所有文件对象

File f = new File(pathSrc);

File[] files = f.listFiles();

//如果目的地的目录不存在则创建

File fileDest = new File(pathDest);

if(!fileDest.exists()){

fileDest.mkdir();

}

//遍历来源中的所有文件对象

for (File file : files) {

//如果是文件夹,则递归

if(file.isDirectory()){

//下级的目录名称是当前目的地目录名称加上,下一个的文件夹名称

method(file.getAbsolutePath(),pathDest + "\\" + file.getName());

}

else{

//如果是文件,则复制

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pathDest + "\\" + file.getName()));

byte[] bys = new byte[1024];

int len = 0;

while((len = bis.read(bys)) != -1){

bos.write(bys,0,len);

}

bos.close();

bis.close();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值