zoukankan      html  css  js  c++  java
  • 关于Java中File的renameTo函数

    先看Java编程实战经典中的一道习题:

    编写程序,程序运行时输入目录名称,并把该目录下的所有文件名后缀修改成.txt。

    按照题意,我在d盘新建了文件夹test,并在该文件夹下新建了一个文件file.d。接着我写了如下程序

    import java.io.File;
    import java.util.Scanner;
    
    public class Ex09 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    //		Scanner scan = new Scanner(System.in);
    //		String dirname = scan.nextLine();
    //		scan.close();
    		String dirname = null;
    		dirname = "d:"+File.separator+"test";
    		File f = new File(dirname);
    		if (f.isDirectory()) {
    			File[] fileList = f.listFiles();
    			for (File file : fileList) {
    				if (file.isFile()) {
    					String suffix = 
    							file.getName().substring(
    							file.getName().lastIndexOf('.')+1);
    					if (false == "txt".equals(suffix)) {
    						String destName = file.getName().substring(
    								0,file.getName().lastIndexOf('.'));
    						File dest = new File(destName+".txt");
    						file.renameTo(dest);
    					}
    				}
    			}
    		}
    	}
    
    }
    

    经检查,程序没有什么问题,但是文件后缀并没有被修改。

    后来检查才发现 

    File dest = new File(destName+".txt");  这样写虽然不会报错,但是不能表示文件的具体存储位置,需要指明文件的绝对地址才行,

    改成如下代码后问题解决。

    import java.io.File;
    import java.util.Scanner;
    
    public class Ex09 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    //		Scanner scan = new Scanner(System.in);
    //		String dirname = scan.nextLine();
    //		scan.close();
    		String dirname = null;
    		dirname = "d:"+File.separator+"test";
    		File f = new File(dirname);
    		if (f.isDirectory()) {
    			File[] fileList = f.listFiles();
    			for (File file : fileList) {
    				if (file.isFile()) {
    					String suffix = file.getName().substring(
    							file.getName().lastIndexOf('.')+1);
    					if (false == "txt".equals(suffix)) {
    						String s = file.getParent();
    						String destName = file.getName().substring(
    								0,file.getName().lastIndexOf('.'));
    						File dest = new File(s+file.separator+destName+".txt");
    						
    						file.renameTo(dest);	
    					}
    				}
    			}
    		}
    	}
    
    }

    可以看出, renameTo这个函数是可以实现将文件重命名和文件移动的功能的。

  • 相关阅读:
    《C语言》for语句(8)
    解决vue vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in nextTick: “TypeError: Cannot convert undefine
    React中WebSocket使用以及服务端崩溃重连
    React Native 中 react-navigation 导航器的使用 [亲测可用]
    ueditor 修改内容方法报错no funtion解决方式
    nodeJs与elementUI实现多图片上传
    Vue多页面开发案例
    Vue.js Cli 3.0 多页面开发案例解析
    基于node.js 微信支付notify_url回调接收不到xml
    react-image-gallery 加入视频图片混合显示
  • 原文地址:https://www.cnblogs.com/aituming/p/4792119.html
Copyright © 2011-2022 走看看