android - 将 json 保存到外部存储器现在不起作用

标签 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)

最佳答案

类似的东西:

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

关于android - 将 json 保存到外部存储器现在不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9497578/

相关文章:

json - 将客户端 Json 下载为 CSV

java - Android 将我的应用程序添加到库中的 "Share"按钮

android - "appcompat_v7"Eclipse新建项目后自动创建项目

java - 我的 JSON 文件太大,无法放入内存,我该怎么办?

reactjs - 如何在 onClick 事件处理程序中识别在同一张 map (使用 react-leaflet)上绘制的许多多边形中单击了哪个?

Java,保存具有多个属性的数据的有效方法是什么?

java - 如何在 Spring Data JPA 中将数据保存到新行中?

python - 指定时间内保存9600端口数据

java - Android 用图标构建迷你抽屉导航

android - 将投影坐标转换​​为 android 中的常规 GPS