获取本地Android项目文件的文件路径

Joh*_*rts 6 java android file

我想以编程方式访问将包含在我的项目文件夹中的特定文件。有没有办法做到这一点?如果是这样,我将文件放在项目文件夹中的什么位置,获取其文件路径的简单代码是什么?

private void saveFileToDrive() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    java.io.File spreadsheet = new java.io.File("Untitled spreadsheet.xlsx");
                    String filePath = spreadsheet.getAbsolutePath();
                    System.out.println("file path is"+filePath);

                    URL fileURL = getClass().getClassLoader().getResource("Untitled spreadsheet.xlsx");
                    String filePath2 = fileURL.getPath();
                    System.out.println("file path2 is"+filePath2);

                    java.io.File fileContent = new java.io.File(filePath);
                    FileContent mediaContent = new FileContent("application/vnd.ms-excel", fileContent);

                    File body = new File();
                    body.setTitle(fileContent.getName());
                    body.setMimeType("application/vnd.ms-excel");


                    File file = service.files().insert(body, mediaContent).setConvert(true).execute();

                    if (file != null) {
                        showToast("File uploaded: " + file.getTitle());
                    }
                    else
                             ;
                } catch (UserRecoverableAuthIOException e) {

                    startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
Run Code Online (Sandbox Code Playgroud)

Yog*_*ngh 5

将文件放在项目的根文件夹中。然后获取文件 URL、路径和其他详细信息:

   File file = new File("test.txt");
   String filePath = file.getAbsolutePath();
Run Code Online (Sandbox Code Playgroud)

编辑: 替代方式(如果文件在您的类路径中,例如将文件放在“src”文件夹中,并确保编译后将其移动到“bin”或“classes”文件夹中):

  URL fileURL = getClass().getClassLoader().getResource(fileName);
  String fileName = fileURL.getFile();
  String filePath = fileURL.getPath();
Run Code Online (Sandbox Code Playgroud)