![](/img/trans.png)
[英]How to move all files from source directory to destination directory, keeping existing files in destination directory, using Java NIO?
[英]Java - Move and Rename all files from one destination to another
我有一個文件夾中的文件,我想將它們移動到另一個文件夾,但也要重命名它們(帶有一些應添加的靜態前綴值)
我成功列出了源目錄中的所有文件,但是在獲取files[i]
時找不到move
方法files[i]
,我也找不到如何在同一時間重命名和移動文件到另一個文件夾。
有人可以告訴我在getFiles
方法中應該添加什么以便移動和重命名。
這是我的班級。
import java.io.File;
public class CopyTest {
static File mainFolder = new File("F:\\TestCopy");
static File destinationFolder = new File("F:\\TestCopy2");
public String prefix="PREFIX";
public static void main(String[] args)
{
CopyTest lf = new CopyTest();
lf.getFiles(lf.mainFolder);
long fileSize = mainFolder.length();
System.out.println("File size in KB is : " + (double)fileSize/1024);
}
public void getFiles(File f){
File files[];
if(f.isFile())
System.out.println(f.getAbsolutePath());
else{
files = f.listFiles();
for (int i = 0; i < files.length; i++) {
getFiles(files[i]);
}
}
}
}
您可以使用file.renameto()
進行移動和重命名。
樣品 -
import java.io.File;
public class MoveFileExample
{
public static void main(String[] args)
{
try{
File afile =new File("C:\\folderA\\Afile.txt");
if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
yourFile.renameTo(new File("C://newpath.txt'));
怎么yourFile.renameTo(new File("C://newpath.txt'));
您可以在new File(...)
重命名它,因此請獲取文件名並添加前綴。
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html嘗試類Files move()方法。
你可以這樣寫
import java.io.File;
public class CopyTest
{
static File mainFolder = new File("F:\\TestCopy");
static File destinationFolder = new File("F:\\TestCopy2");
public String prefix = "PREFIX";
public static void main(String str[])
{
CopyTest lf = new CopyTest();
lf.getFiles(lf.mainFolder);
long fileSize = mainFolder.length();
System.out.println("File size in KB is : " + (double) fileSize / 1024);
}
public void getFiles(File f)
{
File files[];
if (f.isFile())
{
f.renameTo(new File(destinationFolder + "\\" + prefix + f.getName()));
}
else
{
files = f.listFiles();
for (int i = 0; i < files.length; i++)
{
getFiles(files[i]);
}
}
}
}
將文件從一個文件夾復制到另一個文件夾然后刪除源文
/**
* Copy File From One Folder To Another Folder
* Then Delete File
* @param sourceFile
* @param destFile
* @throws IOException
*/
public static void copyFile(File sourceFile, File destFile) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(sourceFile);
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} catch(Exception e){
e.printStackTrace();
}
finally
{
in.close();
out.close();
sourceFile.delete();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.