开发者

Android: can not write to a txt file

My program contains a file with the name "size.txt", which contains just a word "15". If a user choose a value from a spinner,say 17, then the chosen value should be stored in the file and replace "15".

I have added the permission to the program

<开发者_运维百科uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

But somehow i can not make the chosen value be written to the file. Here is my code

try {
    FileOutputStream fos = openFileOutput("size", Context.MODE_PRIVATE);
    OutputStreamWriter osw = new OutputStreamWriter(fos);
    osw.write("17");
    osw.flush();
    osw.close();
} catch (java.io.IOException e) {
//do something if an IOException occurs.
}

Can anybody help me? Thank youvery much!


Maybe you should read this, before looking for a way to fix your code.

According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,

Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.

Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.

  1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.

  2. Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.

Shared Preferences:

The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.

(1) Here is how you get the instance when you specify the file name

public static final String PREF_FILE_NAME = "PrefFile";
   SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.

(2) The recommended way is to use by the default mode, without specifying the file name

SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context);

Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:

 int storedPreference = preferences.getInt("storedInt", 0);

To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.

SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

Editor also support methods like remove() and clear() to delete the preference value from the file.

Activity Preferences:

The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.

Following is the code to get preferences

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);

The code to store values is also same as in case of shared preferences.

SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.

To see some more examples check Android's Data Storage post on developers site.


*package com.example;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class GetFromURLActivity extends Activity 
{   
    TextView txtContent;
    String path;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            //this is the file you want to download from the remote server

            /*path ="http://localhost:82/TextureTest01.apk";*/
            path ="http://10.0.2.2:82/my.txt";
            //this is the name of the local file you will create

            /*String targetFileName = "mynew"; // Omit extension.
            boolean eof = false;*/
            URL u = new URL(path);

            HttpURLConnection c = (HttpURLConnection) u.openConnection();

            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            InputStream in = c.getInputStream();


            Log.e("value",in.toString());

            //Gets the instance of the asset manager
            AssetManager mngr=getAssets();

            //Resources resources = new Resources();
            //resources.getAssets().open("my.txt");
            //FileOutputStream f = new FileOutputStream(new File("c:\\" + targetFileName));

            /*FileOutputStream f = this.openFileOutput(targetFileName,
                    this.MODE_WORLD_READABLE);*/

            ByteArrayOutputStream bo = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            in.read(buffer); //  Read from Buffer.
            bo.write(buffer); // Write Into Buffer.

            /*int len1 = 0;
            while ( (len1 = in.read(buffer)) != -1 ) 
            {
                //f.write(buffer,0, len1);
                bo.write(buffer,0, len1); // Write Into Buffer.
            }*/
            txtContent =(TextView)findViewById(R.id.textview);
            txtContent.setText(bo.toString()); 
            bo.close();
            //f.close();

        } 
        catch (MalformedURLException e) {
             e.printStackTrace();
            //txtContent.setText(e.getMessage().toString());
        } catch (ProtocolException e) {
            e.printStackTrace();
            //txtContent.setText(e.getMessage().toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            //txtContent.setText(e.getMessage().toString());
        } catch (IOException e) {
            e.printStackTrace();
            //txtContent.setText(e.getMessage().toString());
        }
    }
    String ReadFile(InputStream is)
    {
        ByteArrayOutputStream bo=new ByteArrayOutputStream();

        byte [] buffer=new byte[1024];

        try {
            is.read(buffer);
            bo.write(buffer);

            bo.close();
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bo.toString();
    }
}
// My Email Id is muhammad.mubashir.bscs@gmail.com*
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜