【总结】java文件移动

最近自己写代码,主要牵涉到了:文件夹的移动功能

这个是之前转载的:转载的    <-- 很全面、很强大


以下是本人总结的(若有不对之处,请多多指教,谢谢):

  private static void moveToFloder(File pdfName) {

        String oldPath = pdfName.getPath;
        String newPath;
        
        try {
            
            int bytesum = 0;
            int byteread = 0;

            //新建一个文件的路径
            File file =
                    new File(newPath + "\\" + pdfName.getName());
            //判断该路径是否有这个文件
            if (!file.isDirectory()) {

               //可以创建多个文件夹,若出现文件访问失败,则要加上"getParentFile()","mkdir()"只能建立单个的文件夹
               file.getParentFile().mkdirs();
            }

            //找到原文件,读取
            InputStream inStream = new FileInputStream(oldPath);
            //在新的路径下面写入文件,其中FILE对象的path和name用:  "/"    隔开
            FileOutputStream fs =
                    new FileOutputStream(newPath
                        + "/"
                        + pdfName.getName());
            byte[] buffer = new byte[1444];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
            inStream.close();

            //找到旧路径的文件,删除
            File delPdfName = new File(oldPath );
            delPdfName.delete();

        } catch (Exception e) {

                e.printStackTrace();


        }

    }

总结:

1、File file = new File(File pdf);   -->   假若从外面传给pdf这个File对象,那么      pdf=path+"/"+name

2、

 File file =
                    new File(newPath + "\\" + pdfName.getName());   //   -->  这个是建立文件夹的时候用到的
3、path   -->  要以”\\“结尾。

4、多文件加的新建用mkdirs(),

file.getParentFile().mkdirs()     //   -->之所以加上pdfName.getName(),是由于用了"gerParentFile()"方法,该路径才能新建出完整的路径

//例如:    预期:c:\test\MyLove  --> 实际: c:\test\MyLove\1.txt     才会得到预期值。若不加上1.txt,则路径为:c:\test

5、对于mkdirs(),可以查看API去进行


谢谢

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值