将文件从文件夹移动到文件夹

Mat*_*lah 1 directory android gridview file move

我正在创建一个应用程序,在该应用程序中,我在自定义 gridview 中显示来自特定文件夹的图像。我想将单击的项目移动到另一个文件夹。我有来自 gridview 的图像的绝对路径以及我想将文件移动到的文件夹的绝对路径。问题是我不知道如何将文件从存储实际图像的文件夹移动到另一个文件夹。有人可以告诉我代码或类的帮助,我可以将文件从文件夹移动到文件夹。我在 stackoverflow 上搜索了很多并找到了一些代码,但这对我的案例不起作用。

Tom*_*erZ 6

你有两种方式:

1:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

2:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

代码示例取自此处:http : //www.mkyong.com/java/how-to-move-file-to-another-directory-in-java/