2

I'm developing a simple android application which needs a text file access! I'm getting filenotfoundexception even though I specified the absolute path of the file in File constructor. My code is

`File fr = new File("C:/mywork1/Dictionary/src/com/praveen/dictionary/vsn.txt");
                System.out.println(fr.getAbsolutePath());
                Scanner bb = new Scanner(fr);
                System.out.println(fr.exists());
                while((strf = bb.nextLine()) != null)
                {...

Some previous questions have answers that suggest using AssetsManager instead. I tried that.

AssetManager assetManager = Context.getAssets();
InputStream in = null;
in = assetManager.open("vsn.txt");

the error I'm getting for this code is

"cannot make static reference to a non static variable"

At the first line. Kindly help me out with this problem.. I can't even use throws clause since I'm using onCreate method! I changed the settings in the run configuration so that current working directory will contain my text file. Thanks

Roham Rafii
  • 2,929
  • 7
  • 35
  • 49
  • 5
    Why did you think an Android device has a `C` unit to begin with? – Luiggi Mendoza Jun 10 '13 at 07:22
  • @LuiggiMendoza :D +1. Amazing mistake – Pankaj Kumar Jun 10 '13 at 07:23
  • 1
    Try `AssetManager assetManager = yourContextObject.getAssets();` – Alexis C. Jun 10 '13 at 07:23
  • @ZalaJanaksinh that's not an excuse to use `C` unit in code. – Luiggi Mendoza Jun 10 '13 at 07:25
  • Android is not .... You know.. – Glenn Jun 10 '13 at 07:26
  • @LuiggiMendoza: wanted to specify the absolute path.. That's my drive name!I tried this out of curiosity..anyways ,even if i specify only filename i get the same error. Suggest any changes in absolute path. – Narasimhan V s Jun 10 '13 at 07:26
  • Even in Windows, you should not use the disk unit to refer for absolute paths. You should use `/an/absolute/path/like/this` instead, the JVM in Windows will handle the unit where the application is running (`C`, `D`, etc). – Luiggi Mendoza Jun 10 '13 at 07:28
  • @PankajKumar: I need a suggestion for my question!!! – Narasimhan V s Jun 10 '13 at 07:29
  • @NarasimhanVs Use The [Environment](http://developer.android.com/reference/android/os/Environment.html) class of Android Framework. There are methods which can help you to access like the external storage. Please read it! – Glenn Jun 10 '13 at 07:30
  • Please first let us know where is this *vsn.txt* file: inside your project/application resources? inside the Android device? inside an external storage sd card? – Luiggi Mendoza Jun 10 '13 at 07:34
  • @LuiggiMendoza Its inside my src folder where other java files are kept!Should i keep it under resources? If yes where in resources directory i should place the file? – Narasimhan V s Jun 10 '13 at 07:36
  • @NarasimhanVs Put that file in `asset` directory not in `src` and, refer to @ZouZou's answer to retrieve that file at runtime . – Glenn Jun 10 '13 at 07:39
  • @ZouZou: i tried that in my code specified above! what is "yourContextObject"? I used Context.. Im getting the error as specified.. – Narasimhan V s Jun 10 '13 at 07:39
  • 1
    @NarasimhanVs If you don't have a contextObject and you're in a class that extends activity, you could use `getActivity().getAssets();` – Alexis C. Jun 10 '13 at 07:40
  • @system32: yes it tried that. I used Context as my contextobject and im getting "cannot make static reference to a non static variable".. – Narasimhan V s Jun 10 '13 at 07:41
  • I solved.. I used AssetManager and BufferedReader!! Thanks to Everyone who helped me... – Narasimhan V s Jun 10 '13 at 09:36

4 Answers4

2

An Android device wont save or read to a file that is in a C: Directory.

You have to move it into your Resources folder within the project and include it that way.

gavlaaaaaaaa
  • 612
  • 2
  • 7
  • 11
2

Android is based on Linux and therefore doesn't use a filesystem with drive letters like c:\ etc.

If you want to open a file it depends where it is. If you have it in your assets directory you use the AssetsManager. The reason why you can do it the way you tried is because you call the method on the class and not the object. If the code is in an Activity simply do:

getAssets().open("vsn.txt");

in a Fragment do:

getActivity().getAssets().open("vsn.txt");

If you want access to the external files directory call getExternalFilesDir(null) on your Context object.

Daniel Lerps
  • 5,256
  • 3
  • 23
  • 33
0

Use the external storage sd card to file creation and deletion.. Use standard Java I/O. Use Environment.getExternalStorageDirectory() to get to the root of external storage (which, on some devices, is an SD card).

below is a function that will programmatically move your file

set the correct permissions in the manifest

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


private void moveFile(String inputPath, String inputFile, String outputPath) {

    InputStream in = null;
    OutputStream out = null;
    try {

        //create output directory if it doesn't exist
        File dir = new File (outputPath); 
        if (!dir.exists())
        {
            dir.mkdirs();
        }


        in = new FileInputStream(inputPath + inputFile);        
        out = new FileOutputStream(outputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;

            // write the output file
            out.flush();
        out.close();
        out = null;

        // delete the original file
        new File(inputPath + inputFile).delete();  


    } 

         catch (FileNotFoundException fnfe1) {
        Log.e("tag", fnfe1.getMessage());
    }
          catch (Exception e) {
        Log.e("tag", e.getMessage());
    }

}

To Delete the file use

private void deleteFile(String inputPath, String inputFile) {
    try {
        // delete the original file
        new File(inputPath + inputFile).delete();  


    }
   catch (FileNotFoundException fnfe1) {
        Log.e("tag", fnfe1.getMessage());
    }
    catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
}

To copy

private void copyFile(String inputPath, String inputFile, String outputPath) {

    InputStream in = null;
    OutputStream out = null;
    try {

        //create output directory if it doesn't exist
        File dir = new File (outputPath); 
        if (!dir.exists())
        {
            dir.mkdirs();
        }


        in = new FileInputStream(inputPath + inputFile);        
        out = new FileOutputStream(outputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;

            // write the output file (You have now copied the file)
            out.flush();
        out.close();
        out = null;        

    }  catch (FileNotFoundException fnfe1) {
        Log.e("tag", fnfe1.getMessage());
    }
            catch (Exception e) {
        Log.e("tag", e.getMessage());
    }

}
Venkatesh S
  • 5,466
  • 1
  • 25
  • 30
  • i need a simple text file for my dictionary program! Wats the part of sdcard in it? Y cant i simply make modifications to the code i specified to get the desired result? I kept my text file inside src folder which contain other java files.. Is that ri8? – Narasimhan V s Jun 10 '13 at 07:35
0

You can put your text file @sdcard or @assets folder in android application. To access file from sdcard is mention Android: How to access a file in the SD Card & to access file from assests folder mention in this link Android - Access file from assets \ PDF display

Community
  • 1
  • 1
chaitanya
  • 1,726
  • 2
  • 17
  • 13