如何将文件和目录移动到Java中的另一个目录中?我正在使用这种技术进行复制,但我需要移动:
File srcFile = new File(file.getCanonicalPath());
String destinationpt = "/home/dev702/Desktop/svn-tempfiles";
copyFiles(srcFile, new File(destinationpt+File.separator+srcFile.getName()));
答案 0 :(得分:3)
你可以试试这个:
srcFile.renameTo(new File("C:\\folderB\\" + srcFile.getName()));
答案 1 :(得分:2)
你读过这个“http://java.about.com/od/InputOutput/a/Deleting-Copying-And-Moving-Files.htm “
Files.move(original, destination, StandardCopyOption.REPLACE_EXISTING)
将文件移至目的地。
如果要移动目录 使用此
File dir = new File("FILEPATH");
if(dir.isDirectory()) {
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++) {
//move files[i]
}
}
答案 2 :(得分:1)
Java.io.File不包含任何现成的make move文件方法,但您可以使用以下两种方法解决此问题:
File.renameTo()
复制到新文件并删除原始文件。
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();
}
}
}
复制和删除
public class MoveFileExample
{
public static void main(String[] args)
{
InputStream inStream = null;
OutputStream outStream = null;
try{
File afile =new File("C:\\folderA\\Afile.txt");
File bfile =new File("C:\\folderB\\Afile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
System.out.println("File is copied successful!");
}catch(IOException e){
e.printStackTrace();
}
}
}
希望它能帮助:)