關於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這個函數是可以實現將文件重命名和文件移動的功能的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM