2013-04-14 60 views
0

我一直在試圖製作一個程序,將幾個.mp4文件重命名爲它所在文件夾的名稱。該程序有時會在幾個文件中工作,但最終會拋出空指針異常將多個文件重命名爲Windows上的文件夾名稱

我已經嘗試了多種不同的方式,但似乎沒有正常工作,我不是很熟悉Windows 7相關的Java。

有人可以看到問題嗎?乾杯。

public static void main (String []args) throws InterruptedException 
{ 
String dir = "D:\\New folder"; 

File directory = new File(dir); 
File[] files = directory.listFiles(); 

File tempd; 
File[] tempf; 
String temps; 
int filecount = 0; 

for (int index = 0; index < files.length; index++) 
{  
temps = files[index].toString(); 
tempd = new File(temps); 
tempf = tempd.listFiles(); 

for (int i = 0; i < tempf.length; i++) 
{ 
String[] tempsRel = temps.split("\\\\"); 

if (tempf[i].toString().endsWith("mp4")) 
{ 
boolean success = tempf[i].renameTo(new File(dir + "\\" + tempsRel[tempsRel.length-1] + ".mp4")); 
if (success) 
{ 
System.out.println("RENAMED FILE ==> " + tempsRel[tempsRel.length-1] + ".mp4"); 
}}}} 

System.exit(0); 
} 
+0

請發送堆棧跟蹤。 – AlexR

回答

0

聽起來你有一些文件裏面新建文件夾

tempf = tempd.listFiles(); 

上市內

tempd = new File(temps); 
    if (tempd.isDirectory()) { 
    your code 
    } 
文件之前,如果tempd是目錄這條線將返回null,如果你有新的文件夾 檢查內部文件
+0

感謝堆,這個解決方案完美無缺! – user2279253

0

重命名目錄中的所有文件

import java.io.File; 
import java.util.Scanner; 

public class RENAME { 
public static void main(String[] args) { 
    Scanner s = new Scanner(System.in); 
    System.out.print("Enter folder name "); 
    File old = new File(s.nextLine()); 
    for(File f :old.listFiles()){ 
     if(f.isFile()) 
     { 

      f.renameTo(new File(f+".png")); 

     } 
    } 
    } 
} 
} 
相關問題