簡體   English   中英

獲取絕對路徑並移動文件

[英]Get absolute path and move file

我是android編程的新手。 我正在創建一個應用程序,在該應用程序中我應該從Custom Gallery獲取文件的絕對路徑,然后將該文件移至私有文件夾。 我進行了很多搜索,但找不到任何完美的答案。 請幫助我編寫代碼。 謝謝。

獲取SD卡的絕對路徑:

String SDCARD_PATH = Environment.getExternalStorageDirectory().getPath() + "/";


File dirFolder = new File(path);

File[] folders = dirFolder.listFiles(); // list of all files and folder into this path
for (File file : folders) {
    if (file.isDirectory()) {
        file.getName() // this will return folder name
    } else {
        file.getName(); // this will return file name with extension
    }
}

在整個過程中執行遞歸方法。

復制文件:

private void copyDataBase() throws IOException {

        // Open your local db as the input stream
        InputStream myInput = new FileInputStream(filePath + fileNameWithExtension);

        // Path to the just created empty db
        String outFileName = OUTPUT_PATH + "/" + FILE_NAME;

        // Open the empty db as the output stream
        new File(outFileName).createNewFile();
        OutputStream myOutput = new FileOutputStream(outFileName);

        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

之后,如果需要,只需刪除文件:

String myFile = filePath+"/"+fileNameWithExtension;
if (new File(myFile).delete())
            // do something
        else
            // do something

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM