1

here is what I am doing :

1- Getting a file from my assests and put it into a String - SUCCESSFUL

2- Make A file in getFilesDir() - FAILS (No crash yet)

3- Write the string I got to this file using a FileWriter - FAILS (No crash yet)

4- Read the new File that I have just made - FAILS (throws NoSuchElementException)

Here are the stuff you gotta see :

A small useful method which i used :

public String inputStreamToString(InputStream stream){

        Scanner s = new Scanner(stream).useDelimiter("\\A");
        String aa = s.next();
        return aa;

    }

Snippet of MainActivity.java :

//B2 and text are a well defined Button and TextView respectively, ensured through previous testings
B2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                AssetManager as = getAssets();
                InputStream stream = null;
                try {
                    stream = as.open("updater-script");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Scanner s = new Scanner(stream).useDelimiter("\\A");
                String aa = s.next();
                text.setText(aa);

                File file = new File(getFilesDir() + "/updater-script");
                try {
                    boolean b = file.createNewFile(); //returns false, indicating the file wasn't made
                    text.setText(text.getText()+String.valueOf(b));
                    new File(getFilesDir().getAbsolutePath()).mkdirs();
                    FileWriter write = new FileWriter(getFilesDir().toString()+File.pathSeparator+"updater-script");
                    Show(getFilesDir().toString());
                    write.write(aa);
                    write.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                }
        });
        B2.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                File file = new File(getFilesDir(), "updater-script");
                try {
                    FileInputStream in = new FileInputStream(file);
                    String aa = inputStreamToString(in);
                    text.setText(aa);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


                return true;
            }
        });

My Manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="seaskyways.testingproject"
    android:versionCode="1"
    android:versionName="beta" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STROAGE"/>
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.Sherlock" >
        <activity
            android:name="seaskyways.testingproject.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Holo"
            android:uiOptions="splitActionBarWhenNarrow" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="seaskyways.testingproject.MenuActivity"
            android:label="@string/title_activity_menu" >
        </activity>
        <activity
            android:name="seaskyways.testingproject.Splash"
            android:label="@string/title_activity_splash"
            android:theme="@style/Theme.Sherlock.Dialog" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="seaskyways.testingproject.HorizontalScrollView"
            android:label="@string/title_activity_splash" >
            <intent-filter>
                <action android:name="android.intent.action.HSV" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name="seaskyways.testingproject.ExpandableLists"
            android:label="@string/title_activity_expandable_lists"
            android:parentActivityName="seaskyways.testingproject.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="seaskyways.testingproject.MainActivity" />
        </activity>
        <activity
            android:name="seaskyways.testingproject.SwipeStrips"
            android:label="@string/title_activity_swipe_tabs"
            android:parentActivityName="seaskyways.testingproject.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="seaskyways.testingproject.MainActivity" />
        </activity>
        <activity
            android:name="seaskyways.testingproject.SwipeTabs"
            android:label="@string/title_activity_swipe_tabs"
            android:parentActivityName="seaskyways.testingproject.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="seaskyways.testingproject.MainActivity" />
        </activity>
    </application>

</manifest>

Stack Trace :

03-11 21:23:08.241: E/AndroidRuntime(3958): FATAL EXCEPTION: main
03-11 21:23:08.241: E/AndroidRuntime(3958): java.util.NoSuchElementException
03-11 21:23:08.241: E/AndroidRuntime(3958):     at java.util.Scanner.next(Scanner.java:1007)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at java.util.Scanner.next(Scanner.java:980)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at seaskyways.testingproject.MainActivity.inputStreamToString(MainActivity.java:44)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at seaskyways.testingproject.MainActivity$7.onLongClick(MainActivity.java:171)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at android.view.View.performLongClick(View.java:4240)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at android.widget.TextView.performLongClick(TextView.java:8060)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at android.view.View$CheckForLongPress.run(View.java:17339)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at android.os.Handler.handleCallback(Handler.java:725)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at android.os.Handler.dispatchMessage(Handler.java:92)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at android.os.Looper.loop(Looper.java:137)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at android.app.ActivityThread.main(ActivityThread.java:5237)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at java.lang.reflect.Method.invokeNative(Native Method)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at java.lang.reflect.Method.invoke(Method.java:511)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
03-11 21:23:08.241: E/AndroidRuntime(3958):     at dalvik.system.NativeStart.main(Native Method)

Please no workarounds , because I have future plans ... Thanks for any help ! If you need any more info am here , and the comment box is a few centimeters down :P

Seaskyways
  • 3,630
  • 3
  • 26
  • 43
  • Your logcat is actually suggesting your error is at s.next(); – DigCamara Mar 11 '13 at 19:50
  • 1
    **boolean b = file.createNewFile(); //returns false, indicating the file wasn't made** - Read the docs for `createNewFile()` http://developer.android.com/reference/java/io/File.html#createNewFile() If the file can't be created, it will throw an `IOException`. If you're getting `false` as a return on the call and no exception then it's because the file already exists. – Squonk Mar 11 '13 at 20:18
  • or, like my amended answer indicates, because the permissions are slightly wrong... – DigCamara Mar 11 '13 at 20:26
  • @DigCamara : `getFilesDir()` returns a path on the internal storage so permissions for writing to the external storage are not required. But you are correct about the typo in the manifest. – Squonk Mar 11 '13 at 20:29
  • Well, if the last suggestion fails, I'll leave this question with the advice someone else gave someone who also couldn't create files using those instructions: http://stackoverflow.com/questions/1525060/file-createnewfile-thowing-ioexception-no-such-file-or-directory – DigCamara Mar 11 '13 at 20:34
  • It seems to me just using `openFileOutput(...)` and `openFileInput(...)` would make most sense. – Squonk Mar 11 '13 at 20:40
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/25984/discussion-between-digcamara-and-squonk) – DigCamara Mar 11 '13 at 21:46
  • @Squonk , yes , I went to the directory where the file should be (as root) , and I found my file (updater-script) there with 0kb size , this leaves that the problem is in writing to the file ... For the record , I decompiled some app that uses the functionality i need (using a specialized decompiler from apk to source) , it doesn't use any permission to write a file to getFilesDir() , it does it plainly ! I will see your suggestion Squonk ! Thanks for help guys ! – Seaskyways Mar 12 '13 at 11:51
  • @Squonk , nop , openFileInput doesn't take path seperators , which will throw an IllegalArguementException ... – Seaskyways Mar 12 '13 at 12:03
  • 1
    @Seaskyways : **"nop , openFileInput doesn't take path seperators "** - Yes, I know that. Don't use a path separator just use the filename. The whole point about `openFileInput(...)` and `openFileOutput(...)` is they are helper methods which abstract the need to know anything about a file's path and the directory it is read from / written to. – Squonk Mar 12 '13 at 16:03

2 Answers2

1

From this documentation I understand that you should actually protect your .next() invocations with .hasNext().

Here, for instance:

public String inputStreamToString(InputStream stream){

    Scanner s = new Scanner(stream).useDelimiter("\\A");
    if (s.hasNext()){
       return s.next();
    }else{
       return null;
    }       
}

And, if your permissions are written correctly, this

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

permission doesn't actually exist. It should be

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
DigCamara
  • 5,540
  • 4
  • 36
  • 47
  • If you read what I wrote well , you should have known that my stack trace points to my `s.next()` because `boolean b =file.createNewFile();` return false , indicating the file wasn't created , meaning that my scanner won't find any "next()" , causing an exception ... This isn't an answer , this will cause me to have a NullPointerException ... – Seaskyways Mar 11 '13 at 20:03
  • You're right. And I added a new section to my answer, which might actually explain why you don't have rights to create a file. If that doesn't do the trick, I'll gladly withdraw my answer. – DigCamara Mar 11 '13 at 20:26
  • You might have to clean the project and reinstall it. Eclipse is not very good at detecting changes made to the Manifest (if you're using Eclipse, of course) – DigCamara Mar 11 '13 at 20:29
0

I said :" boolean b = file.createNewFile(); //returns false, indicating the file wasn't made " which isn't true , b = false without any exceptions means that the file is already made ... But the crash was caused because the File that was created doesn't have any text to be read , which will , yea , cause a crash , since am reading nothing ...

So to correct it , I don't need any permissions , just Java ... All I have to do is either write something to that file before trying to read it or program my class which gives me a String of an InputStream to return something instead of nothing and crashing :

So the first solution is like this :

File file = new File(get_data_dir(getApplicationContext()), "updater-script");
                try {

                    InputStream stream = null;
                    try {
                        stream = getAssets().open("updater-script");
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    FileOutputStream ou = new FileOutputStream(file);
                    byte[] buffer = inputStreamToString(stream).getBytes();
                    ou.write(buffer);//Now the file has something to be read ...


                    FileInputStream in = new FileInputStream(file);



                    String aa = inputStreamToString(in);

And the second Solution which seems to be easier is this :

public String inputStreamToString(InputStream stream){
        String aa;
        Scanner s = new Scanner(stream).useDelimiter("\\A");
        if(s.hasNext()){
            aa = s.next();
        }else{
            aa = "";
        }

        return aa;//Now it returns something no matter what ...

    }
Seaskyways
  • 3,630
  • 3
  • 26
  • 43