保存到外部内存android

时间:2012-02-29 00:01:33

标签: android memory external save

嘿有男人和女孩我有这个应用程序我需要将json文件保存到外部存储器,iv完成外部检查但是看起来很难找到下一步该做什么的教程,这是我的代码... < / p>
    public class MainActivity extends Activity {

String entityString = null;
String storyObj = "";
Object json = null;
HttpEntity entity = null;
InputStream is = null;
Integer responseInteger = null;

//external storage check
boolean storageAvailable = false;
boolean storageWriteable = false;
String state = Environment.getExternalStorageState();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button downloadBtn = (Button) findViewById(R.id.downloadButton);
    downloadBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            saveToExternal();

        }
    });

    Button loadBtn = (Button) findViewById(R.id.loadButton);
    loadBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            loadExternal();

        }
    });


 //end of onCreate()   
}


public void saveToExternal(){
    TextView test = (TextView) findViewById(R.id.textView);


    try{
        //connects to mySQL
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
        HttpResponse response = client.execute(post);
        //captures the response
        entity = response.getEntity();
        InputStream entityStream = entity.getContent();
        StringBuilder entityStringBuilder = new StringBuilder();
        byte [] buffer = new byte[1024];
        int bytesReadCount;
        while ((bytesReadCount = entityStream.read(buffer)) > 0)  {
            entityStringBuilder.append(new String(buffer, 0, bytesReadCount));
        }
        entityString = entityStringBuilder.toString();
        //responseInteger = Integer.valueOf(entityString);
    }catch(Exception e) {
         Log.e("log_tag", "Error in http connection "+e.toString());
    }

    //writes as String from entityString to external memory

    //first check storage state
    try{

        if (Environment.MEDIA_MOUNTED.equals(state)){
            storageAvailable = storageAvailable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
            storageAvailable = true;
            storageWriteable = false;
        } else storageAvailable = storageWriteable = false;









    }catch(Exception e) {
         Log.e("log_tag", "Error saving string "+e.toString());
    }

//end of saveJson()
}

public void loadExternal(){
    TextView test = (TextView) findViewById(R.id.textView);


    //loads the files
    try{
        FileInputStream fileInput = openFileInput("story.json");

        BufferedReader inputReader = new BufferedReader(new InputStreamReader(fileInput, "UTF-8"), 8);
        StringBuilder strBuilder = new StringBuilder();
            String line = null;
            while ((line = inputReader.readLine()) != null) {
                strBuilder.append(line + "\n");
            }
            fileInput.close();
            storyObj = strBuilder.toString();

    }catch(IOException e){
         Log.e("log_tag", "Error building string "+e.toString());
    }

    try{
        JSONArray jArray = new JSONArray(storyObj);
        String storyNames = "";
        for(int i = 0;i<jArray.length();i++){
            storyNames += jArray.getJSONObject(i).getString("story_name") +"\n";
        }
        test.setText(storyNames);

    }catch(JSONException e) {
         Log.e("log_tag", "Error returning string "+e.toString());
    }
    return;
//and of openJson() 
}




//end of class body    
}
检查外部存储后,我需要代码来保存一个json文件,这样我以后可以在我的应用程序中调用它,任何人都可以帮助我吗?我主要不知道如何制作文件路径,然后将其保存到该文件路径,我也是在最佳实践之后...感谢您的时间并帮助每个人

2 个答案:

答案 0 :(得分:1)

您可以尝试:

// Create the file using the SDCard directory
new myFile = File(new File(Environment.getExternalStorageDirectory(), "myfile.json");
// Create an output stream to write the json
FileOutputStream out = new FileOutputStream(myFile)
byte[] b = new byte[4*1024]; // 4k chunks
int read;
while ((read = in.read(b)) > 0) {
   out.write(b, 0, read);
}
out.flush();
out.close();

答案 1 :(得分:0)

这样的事情:

if(storageAvailable && storageWriteable) {
    File extFile = new File(Environment.getExternalStorageDirectory(), "story.json");
    FileOutputStream out = new FileOutputStream(extFile);

    out.write(entityString.getBytes());
    out.flush();
    out.close();
}

另外,您需要将读取方法更改为以下内容:

File extFile = new File(Environment.getExternalStorageDirectory(), "story.json");
FileInputStream fileInput = new FileInputStream(extFile);

便捷方法openFileInput()旨在仅打开内部存储文件目录的文件路径。您需要明确引用外部存储以获取文件流。

您还可以看到两个位置的文件引用相同,因此这应该是类中其他位置的成员定义。

HTH