0

I have been trying to make a program that renames several .mp4 file to the name of the folder it is in.The program works sometimes on a few files but eventually throws a null pointer exception

I have tried multiple different ways but none seem to work properly and I am not very familiar with windows 7-relevant java.

Can anybody see the problem? Cheers.

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);
}
4

2 回答 2

0

听起来你在新文件夹中有一些文件

  tempf = tempd.listFiles();

如果您在新文件夹中有文件,此行将返回 null 在列出文件之前检查 tempd 是否是目录

  tempd   = new File(temps);
  if (tempd.isDirectory()) { 
   your code
  }
于 2013-04-14T09:20:56.643 回答
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"));

      }
   }
  }
 }
}
于 2015-08-18T04:48:14.293 回答