使用.txt文件中的字符串列表重命名已知文件

时间:2016-05-28 18:47:21

标签: java text-files rename

我试图编写一个代码,让我可以使用txt文件重命名特定文件(具有已知名称和目录),该文件中包含名称列表。具体来说,我想使用包含该季节所有剧集名称的txt文件重命名剧集。

这是我写的代码: 主要课程:

import java.io.IOException;


public class Main {

    public static void main(String[ ] args) throws IOException {
            String file_name = "C:/Users/home/Desktop/Friends season 2 titles.txt";
            try {
                ReadFile file = new ReadFile (file_name);
                String[] arrLines = file.OpenFile();
                int i;
                /*for ( i=0; i < arrLines.length; i++ ) { // perhaps i'll use this loop later on...
                System.out.println( arrLines ) ;
                }
                */
                RenameFile newFile = new RenameFile ();
                String file2_name = "C:/Users/home/Desktop/friends_s02e01_720p_bluray_sujaidr.mkv";
                newFile.RenameSingleFile(arrLines[0], file2_name);
            }
            catch (IOException e) {
                System.out.println(e.getMessage());

            }
    }
}

ReadFile类:

    import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

public class ReadFile {
    private String path;
    public ReadFile(String filePath){
        path = filePath;
    }
    int readLines() throws IOException {
        FileReader file_to_read = new FileReader(path);
        BufferedReader bf = new BufferedReader(file_to_read);

        @SuppressWarnings("unused")
        String aLine;
        int numOfLines = 0;

        while ((aLine = bf.readLine()) != null){
            numOfLines++;
        }
        bf.close();
        return numOfLines;

    }
    public String[] OpenFile() throws IOException {


        FileReader fr = new FileReader(path);
        BufferedReader textReader = new BufferedReader(fr);

        int numberOfLines = readLines();
        String[] textData = new String[numberOfLines];
        for (int i=0; i < numberOfLines; i++) {
        textData = textReader.readLine();
        }
        textReader.close( );
        return textData;
    }

}

RenameFile类:

import java.io.File;
public class RenameFile {
    public void RenameSingleFile(String file1_path, String file2_path){
        File oldName = new File (file1_path);
        File newName = new File (file2_path);

        if(oldName.renameTo(newName)) {
             System.out.println("The file has been renamed to: " +newName);
          } else {
             System.out.println("The file could not be renamed.");
          }
    }   
}

出于某种原因,当我运行此程序时,我在控制台中收到此消息: &#34;无法重命名文件。&#34;,这意味着我的RenameSingleFile方法(或者使用该方法的参数file1_path和file2_path)出现了问题。

我不知道这段代码有什么问题......

1 个答案:

答案 0 :(得分:1)

RenameSingleFile方法中,您应该将file2_name(要重命名的标题)作为第一个参数,并在命名时包含目录路径和文件类型:

newFile.RenameSingleFile(file2_name, "C:/Users/home/Desktop/" + arrLines[0] + ".mkv")