2013-04-14 59 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")); 

     } 
    } 
    } 
} 
} 
相关问题