将json保存到外部存储器现在无法工作

时间:2012-02-29 10:41:34

标签: android json save external

我认为这是有效但现在不行,只是想下载然后打开下载 iv添加了一些coe

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 = storageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
            storageAvailable = true;
            storageWriteable = false;
        } else storageAvailable = storageWriteable = false;


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

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




    }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("/android/data/com.game/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    
}

错误说它没有文件story.json有没有人知道我缺少什么代码来解决这个问题?我的错误现在是

 Error saving string java.io.FileNotFoundException: /mnt/sdcard/android/data/com.game/story.json (No such file or directory)

2 个答案:

答案 0 :(得分:1)

类似的东西:

..........
String content = loadFromHttp();
savedToExternal(content, "story.json");
String res = loadFromExternal("story.json");  
..........  


private void savedToExternal(String content, String fileName) {
    FileOutputStream fos = null;
    Writer out = null;
    try {
        File file = new File(getAppRootDir(), fileName);
        fos = new FileOutputStream(file);
        out = new OutputStreamWriter(fos, "UTF-8");

        out.write(content);
        out.flush();
    } catch (Throwable e){
        e.printStackTrace();
    } finally {
        if(fos!=null){
            try {
                fos.close();
            } catch (IOException ignored) {}
        }
        if(out!= null){
            try {
                out.close();
            } catch (IOException ignored) {}
        }
    }
}

private String loadFromExternal(String fileName) {
    String res = null;
    File file = new File(getAppRootDir(), fileName);
    if(!file.exists()){
        Log.e("", "file " +file.getAbsolutePath()+ " not found");
        return null;
    }
    FileInputStream fis = null;
    BufferedReader inputReader = null;
    try {
        fis = new FileInputStream(file);
        inputReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
        StringBuilder strBuilder = new StringBuilder();
        String line;
        while ((line = inputReader.readLine()) != null) {
            strBuilder.append(line + "\n");
        }
        res = strBuilder.toString();
    } catch(Throwable e){
        if(fis!=null){
            try {
                fis.close();
            } catch (IOException ignored) {}
        }
        if(inputReader!= null){
            try {
                inputReader.close();
            } catch (IOException ignored) {}
        }
    }
    return res;
}

public File getAppRootDir() {
    File appRootDir;
    boolean externalStorageAvailable;
    boolean externalStorageWriteable;
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        externalStorageAvailable = externalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        externalStorageAvailable = true;
        externalStorageWriteable = false;
    } else {
        externalStorageAvailable = externalStorageWriteable = false;
    }
    if (externalStorageAvailable && externalStorageWriteable) {
        appRootDir = getExternalFilesDir(null);
    } else {
        appRootDir = getDir("appRootDir", MODE_PRIVATE);
    }
    if (!appRootDir.exists()) {
        appRootDir.mkdir();
    }
    return appRootDir;
}
............

答案 1 :(得分:0)

好的,让我们再试一次,完整代码:

    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(){
    String content = loadFromNet();
    save(content, "story.json");
}

public void loadExternal(){
    TextView test = (TextView) findViewById(R.id.textView);
    String res = load("story.json");
    test.setText(res);
}

private String loadFromNet(){
    String result = null;
    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
        HttpEntity 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));
        }
        result = entityStringBuilder.toString();
        //responseInteger = Integer.valueOf(entityString);
    }catch(Exception e) {
        Log.e("log_tag", "Error in http connection "+e.toString());
    }
    return result;
}

private void save(String content, String fileName) {
    FileOutputStream fos = null;
    Writer out = null;
    try {
        File file = new File(getAppRootDir(), fileName);
        fos = new FileOutputStream(file);
        out = new OutputStreamWriter(fos, "UTF-8");

        out.write(content);
        out.flush();
    } catch (Throwable e){
        e.printStackTrace();
    } finally {
        if(fos!=null){
            try {
                fos.close();
            } catch (IOException ignored) {}
        }
        if(out!= null){
            try {
                out.close();
            } catch (IOException ignored) {}
        }
    }
}

private String load(String fileName) {
    String res = null;
    File file = new File(getAppRootDir(), fileName);
    if(!file.exists()){
        Log.e("", "file " +file.getAbsolutePath()+ " not found");
        return null;
    }
    FileInputStream fis = null;
    BufferedReader inputReader = null;
    try {
        fis = new FileInputStream(file);
        inputReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
        StringBuilder strBuilder = new StringBuilder();
        String line;
        while ((line = inputReader.readLine()) != null) {
            strBuilder.append(line + "\n");
        }
        res = strBuilder.toString();
    } catch(Throwable e){
        if(fis!=null){
            try {
                fis.close();
            } catch (IOException ignored) {}
        }
        if(inputReader!= null){
            try {
                inputReader.close();
            } catch (IOException ignored) {}
        }
    }
    return res;
}

public File getAppRootDir() {
    File appRootDir;
    boolean externalStorageAvailable;
    boolean externalStorageWriteable;
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        externalStorageAvailable = externalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        externalStorageAvailable = true;
        externalStorageWriteable = false;
    } else {
        externalStorageAvailable = externalStorageWriteable = false;
    }
    if (externalStorageAvailable && externalStorageWriteable) {
        appRootDir = getExternalFilesDir(null);
    } else {
        appRootDir = getDir("appRootDir", MODE_PRIVATE);
    }
    if (!appRootDir.exists()) {
        appRootDir.mkdir();
    }
    return appRootDir;
}