【问题标题】:Renaming multiple files to folder names on windows在Windows上将多个文件重命名为文件夹名称
【发布时间】:2013-04-06 12:31:55
【问题描述】:

我一直在尝试制作一个程序,将多个 .mp4 文件重命名为其所在文件夹的名称。该程序有时可以处理几个文件,但最终会引发空指针异常

我尝试了多种不同的方法,但似乎都无法正常工作,而且我对 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);
}

【问题讨论】:

  • 请发送堆栈跟踪。

标签: java windows file nullpointerexception renaming


【解决方案1】:

这会重命名目录中的所有文件

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"));

      }
   }
  }
 }
}

【讨论】:

    【解决方案2】:

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

      tempf = tempd.listFiles();
    

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

      tempd   = new File(temps);
      if (tempd.isDirectory()) { 
       your code
      }
    

    【讨论】:

      猜你喜欢
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多