现在保存JSON外部存储器不工作 [英] saving json to external memory now not working

查看:175
本文介绍了现在保存JSON外部存储器不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是工作,但现在它没有,只是想下载然后打开下载
四,增加了一些COE

 公共类MainActivity延伸活动{字符串entityString = NULL;
串storyObj =;
JSON对象= NULL;
HttpEntity实体= NULL;
InputStream为= NULL;
整数responseInteger = NULL;//外部存储检查
布尔storageAvailable = FALSE;
布尔storageWriteable = FALSE;
字符串状态= Environment.getExternalStorageState();@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);    按钮downloadBtn =(按钮)findViewById(R.id.downloadButton);
    downloadBtn.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(视图v){            saveToExternal();        }
    });    按钮loadBtn =(按钮)findViewById(R.id.loadButton);
    loadBtn.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(视图v){            loadExternal();        }
    });
 //的onCreate结束()
}
公共无效saveToExternal(){
    TextView的测试=(的TextView)findViewById(R.id.textView);
    尝试{
        //连接到MySQL
        HttpClient的客户端=新DefaultHttpClient();
        HttpPost后=新HttpPost(http://10.0.2.2/textures_story_list.php);
        HTT presponse响应= client.execute(岗位);
        //捕获响应
        实体= response.getEntity();
        InputStream的entityStream = entity.getContent();
        StringBuilder的entityStringBuilder =新的StringBuilder();
        字节[]缓冲区=新的字节[1024];
        INT bytesReadCount;
        而((bytesReadCount = entityStream.read(缓冲液))大于0){
            entityStringBuilder.append(新的String(缓冲,0,bytesReadCount));
        }
        entityString = entityStringBuilder.toString();
        // responseInteger = Integer.valueOf(entityString);
    }赶上(例外五){
         Log.e(log_tag,在HTTP连接错误+ e.toString());
    }    //写为String从entityString外部存储器    //首先检查存储状态
    尝试{        如果(Environment.MEDIA_MOUNTED.equals(州)){
            storageAvailable = storageWriteable = TRUE;
        }否则如果(Environment.MEDIA_MOUNTED_READ_ONLY.equals(州)){
            storageAvailable = TRUE;
            storageWriteable = FALSE;
        }其他storageAvailable = storageWriteable = FALSE;
        如果(storageAvailable&安培;&安培; storageWriteable){
            文件extFile =新的文件(Environment.getExternalStorageDirectory(),/android/data/com.game/story.json);
            FileOutputStream中出=新的FileOutputStream(extFile);            out.write(entityString.getBytes());
            了out.flush();
            out.close();
        }
    }赶上(例外五){
         Log.e(log_tag,错误保存字符串+ e.toString());
    }// saveJson结束()
}公共无效loadExternal(){
    TextView的测试=(的TextView)findViewById(R.id.textView);    //加载文件
    尝试{        的FileInputStream的FileInput = openFileInput(/安卓/数据/ com.game / story.json);        的BufferedReader inputReader =新的BufferedReader(新的InputStreamReader(的FileInput,UTF-8),8);
        StringBuilder的strBuilder =新的StringBuilder();
            串线= NULL;
            而((行= inputReader.readLine())!= NULL){
                strBuilder.append(行+\\ n);
            }
            fileInput.close();
            storyObj = strBuilder.toString();    }赶上(IOException异常五){
         Log.e(log_tag,错误建筑物字符串+ e.toString());
    }    尝试{
        JSONArray jArray =新JSONArray(storyObj);
        串storyNames =;
        的for(int i = 0; I< jArray.length();我++){
            storyNames + = jArray.getJSONObject(ⅰ).getString(story_name)+\\ N的;
        }
        test.setText(storyNames);    }赶上(JSONException E){
         Log.e(log_tag,错误返回字符串+ e.toString());
    }
    返回;
//和openJson的()
}
//类体结束
}

错误说,它没有文件story.json没有人知道codeS IM缺少解决这一问题?现在我的错误是

 错误节省字符串java.io.FileNotFoundException:/mnt/sdcard/android/data/com.game/story.json(没有这样的文件或目录)


解决方案

类似的东西:

  ..........
字符串内容= loadFromHttp();
savedToExternal(内容,story.json);
字符串资源= loadFromExternal(story.json);
..........
私人无效savedToExternal(字符串内容,字符串文件名){
    FOS的FileOutputStream = NULL;
    作家出= NULL;
    尝试{
        档案文件=新的文件(getAppRootDir(),文件名);
        FOS =新的FileOutputStream(文件);
        OUT =新OutputStreamWriter(FOS,UTF-8);        out.write(内容);
        了out.flush();
    }赶上(Throwable的E){
        e.printStackTrace();
    } {最后
        如果(FOS!= NULL){
            尝试{
                fos.close();
            }赶上(IOException异常忽略){}
        }
        如果(满分!= NULL){
            尝试{
                out.close();
            }赶上(IOException异常忽略){}
        }
    }
}私人字符串loadFromExternal(字符串文件名){
    字符串资源= NULL;
    档案文件=新的文件(getAppRootDir(),文件名);
    如果(!file.exists()){
        Log.e(,文件+ file.getAbsolutePath()+找不到);
        返回null;
    }
    FIS的FileInputStream = NULL;
    BufferedReader中inputReader = NULL;
    尝试{
        FIS =新的FileInputStream(文件);
        inputReader =新的BufferedReader(新的InputStreamReader(FIS,UTF-8));
        StringBuilder的strBuilder =新的StringBuilder();
        串线;
        而((行= inputReader.readLine())!= NULL){
            strBuilder.append(行+\\ n);
        }
        RES = strBuilder.toString();
    }赶上(Throwable的E){
        如果(FIS!= NULL){
            尝试{
                fis.close();
            }赶上(IOException异常忽略){}
        }
        如果(inputReader!= NULL){
            尝试{
                inputReader.close();
            }赶上(IOException异常忽略){}
        }
    }
    返回水库;
}公共文件getAppRootDir(){
    文件appRootDir;
    布尔externalStorageAvailable;
    布尔externalStorageWriteable;
    字符串状态= Environment.getExternalStorageState();
    如果(Environment.MEDIA_MOUNTED.equals(州)){
        externalStorageAvailable = externalStorageWriteable = TRUE;
    }否则如果(Environment.MEDIA_MOUNTED_READ_ONLY.equals(州)){
        externalStorageAvailable = TRUE;
        externalStorageWriteable = FALSE;
    }其他{
        externalStorageAvailable = externalStorageWriteable = FALSE;
    }
    如果(externalStorageAvailable&安培;&安培; externalStorageWriteable){
        appRootDir = getExternalFilesDir(NULL);
    }其他{
        appRootDir = GETDIR(appRootDir,MODE_PRIVATE);
    }
    如果(!appRootDir.exists()){
        appRootDir.mkdir();
    }
    返回appRootDir;
}
............

i thought this was working but now its not, just suppose to download then open the download iv added some 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    
}

the error says it has no file story.json does anyone know what codes im missing to fix this? my error is now

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

解决方案

Something like that:

..........
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;
}
............

这篇关于现在保存JSON外部存储器不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆