7

I want to programmatically access a specific file which will be included in my project folder. Is there a way to do this? If so, where in my project folder do I put the file, and what is some simple code to get its file path?

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();
    }
John Roberts
  • 5,885
  • 21
  • 70
  • 124

3 Answers3

5

Put the file in root folder of your project. Then get the File URL, Path and other details as:

   File file = new File("test.txt");
   String filePath = file.getAbsolutePath();

EDIT: Alternate way (if the file is in your classpath e.g. put the file in "src" folder, and make sure its moved in "bin" or "classes" folder after compilation):

  URL fileURL = getClass().getClassLoader().getResource(fileName);
  String fileName = fileURL.getFile();
  String filePath = fileURL.getPath();
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • My fileURL is being set to null, although I have put the file in the root folder as you suggested. – John Roberts Nov 29 '12 at 17:05
  • 1
    @JohnRoberts Are you running your program in some IDE e.g. eclipse? – Yogendra Singh Nov 29 '12 at 17:09
  • 1
    @JohnRoberts Do you need to access the file path or file itself? – Yogendra Singh Nov 29 '12 at 17:11
  • 1
    @JohnRoberts Updated the answer with working code. Two options now. Both are working. Try any of them. – Yogendra Singh Nov 29 '12 at 17:31
  • I get FileNotFoundExceptions for both of these methods. For the second method, I get:11-29 14:43:45.189: W/System.err(21133): java.io.FileNotFoundException: /file:/data/app/com.example.drivequickstart-2.apk!/Untitled spreadsheet.xlsx: open failed: ENOENT (No such file or directory). For the first method, I get:11-29 14:50:22.713: W/System.err(22064): java.io.FileNotFoundException: /Untitled spreadsheet.xlsx: open failed: ENOENT (No such file or directory). Also, I notice that my file is not being recreated in the bin folder for the second method. – John Roberts Nov 29 '12 at 19:51
  • I have added the code to my method into the question - I am essentially just driving to upload a file onto Google Drive. – John Roberts Nov 29 '12 at 19:56
  • 1
    This answer is not workable as it ignores the fact that data packaged in this way is not a literal file. – Chris Stratton Oct 31 '14 at 06:45
0

This depends a lot on what type of file you want to access. You can put the file in either assets or an appropriate subdirectory of res (see Difference between /res and /assets directories).

Community
  • 1
  • 1
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • 1
    This is better as a comment and vote-to-close: you are only saying "it depends..." and linking to another answer. – Sam Nov 29 '12 at 00:37
  • 1
    The key point is that while these mechanisms make data available, it is not a java.io.File – Chris Stratton Oct 31 '14 at 06:46
0

So you want to access a file internal to your app; and you want to do so directly, rather, that is, from an Android Context (and then with a [android.|<package_name>.]R.<resource_type>.<resource_name>).

You have two choices as to location: the res/raw folder or assets/ folder (outside of the res parent).

To choose between the two note from https://developer.android.com/guide/topics/resources/providing-resources.html

Arbitrary files to save in their raw form. To open these resources with a raw InputStream, call Resources.openRawResource() with the resource ID, which is R.raw.filename.

However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/). Files in assets/ aren't given a resource ID, so you can read them only using AssetManager.

To access a file in res/raw/ directly rather, that is, from an Android Context (and then with a [android.|<package_name>.]R.<resource_type>.<resource_name>) you can do something like this:

File file = new File("app/src/main/res/raw/country_data_from_world_bank.xml");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
Community
  • 1
  • 1
John Bentley
  • 1,676
  • 1
  • 16
  • 18