将CSV文件移动到java中的另一个文件夹

时间:2014-01-08 16:38:36

标签: java

MoveFiles
moveCSV.moveToNewFolder(源,目的地); - 此方法始终对此文件返回false" REPORT_AUDIT_LOGGING_REPORT_20140102.csv"。 如果我创建任何虚拟CSV文件, 它按预期移动。 有人可以帮我理解这个文件发生的事情吗?

String csvFilename =
    "C:\\Data\\csv_files\\REPORT_AUDIT_LOGGING_REPORT_20140102.csv";
String  OutputfileName = "GISWREPTPD_Output" + getDateTime()+ ".csv";
File outputfile = new File ("C:\\Data\\Output", OutputfileName );

CSVWriter write = new CSVWriter(new FileWriter(outputfile));
CSVReader csvR = new CSVReader(new FileReader(csvFilename), ',', '\'', 1);

File source = new File ("C:\\Data\\csv_files");
File destination = new File ("C:\\Data\\Archive");

------
------

write.close();

MoveFiles moveCSV = new MoveFiles();
moveCSV.moveToNewFolder(source,destination);


MoveFiles.java
===============
public void moveToNewFolder(File source, File destination) throws IOException 
{
for (File files : source.listFiles())
{
System.out.println("File Name:"files);
System.out.println("Renamed:" +
    files.renameTo(new File (destination, files.getName())));   

}
}

Result:
File Name:C:\Data\csv_files\GISWREPTPD_AUDIT_LOGGING_REPORT_20140102.csv
Renamed:false

1 个答案:

答案 0 :(得分:0)

尝试以下示例。我在一本书中找到了这个例子。您可以轻松使用此代码来满足您的需求。

public class FileCopier {
        public static void main(String args[]) throws Exception {
            File inboxDirectory = new File("data/inbox");
            File outboxDirectory = new File("data/outbox");
            outboxDirectory.mkdir();
            File[] files = inboxDirectory.listFiles();
            for (File source : files) {
                if (source.isFile()) {
                    File dest = new File(outboxDirectory.getPath()+ File.separator+ source.getName());
                    copyFIle(source, dest);
                }
            }
        }
        private static void copyFile(File source, File dest) throws IOException {
            OutputStream out = new FileOutputStream(dest);
            byte[] buffer = new byte[(int) source.length()];
            FileInputStream in = new FileInputStream(source);
            in.read(buffer);
            try {
              out.write(buffer);
            } finally {
              out.close();
              in.close();
            }
        }
}