2017-02-10 80 views
0

我目前停留在重命名文件的问题上。添加字符到时间戳

import java.io.File; 
import java.io.IOException; 

public class FileRename { 
    public static void main(String[] argv) throws IOException { 

     File folder = new File("x:\\chadhold\\test\\"); 

     File[] listOfFiles = folder.listFiles(); 
     if(listOfFiles != null){ 

      for (int i = 0; i < listOfFiles.length; i++) { 
       if (listOfFiles[i].isFile()) { 
        File f = new File("x:\\chadhold\\test\\"+listOfFiles[i].getName()); 
        String currentName = f.getName();    
        currentName = currentName.replace(".D**************", ".D******.T********"); 
        f.renameTo(new File("x:\\chadhold\\test\\" + currentName)); 
        // f.renameTo(new File("x:\\chadhold\\test\\" +currentName.substring(0, currentName.lastIndexOf(".")))); 
       } 
      } 
     } 
     System.out.println("conversion is done"); 
    } 
} 

所以我想在这里做的是找到与.D 启动这些文件是最终与时间戳这就是为什么我使用的*****,因为每个文件都将有不同的名称的文件。

我需要放一个.T并从文件名中删除最后2个字符。

希望我解释这足够好!

在此先感谢。

+0

请包括样品输入/输出名称。 – shmosel

+0

您可以使用foo.startsWith(“。D”)来查找适当的字符串,然后使用.substring将字符串的部分连接在一起。 – Compass

+0

AFK0281.EETM.D1TWP015-02.20170208200225253 => AFK0281.EETM.D1TWP015-02.D170208.T200225253 –

回答

0

与其对字符串使用替换方法,不如使用解析文件名并返回新的方法。

public static void main(String[] args) { 
    System.out.println(newFileName("AFK0281.EETM.D1TWP015-02.20170208200225253")); 
} 

private static String newFileName(String currentName) { 
    String[] parts = currentName.split("\\."); 
    String last = parts[parts.length - 1]; 
    parts[parts.length - 1] = "D" + last.substring(2, 8) + ".T" + last.substring(9); 

    StringBuilder sb = new StringBuilder(); 
    for (String s : parts) { 
     sb.append(s).append("."); 
    } 
    String newName = sb.toString(); 
    return newName.substring(0, newName.length() - 1); 
} 

输出是

AFK0281.EETM.D1TWP015-02.D170208.T200225253

+0

对不起,我不是一个Java开发人员。你可以对我提供的代码进行调整吗? –

+0

只是替换你正在用'currentName = newFileName(currentName)替换'' –

+0

StringUtils无法解析。 我感谢你帮助我btw。 –