将获取的字符串存储到Java中的文件中

时间:2013-06-26 20:53:14

标签: java android json fileoutputstream

我正在尝试将从服务器获取的数据保存到文件中,但我无法将其工作。

有人能帮助我吗?是的,我是新手,刚开始学习Java。

这是我的JSON代码......

JSONObject json = new JSONObject(str);
        JSONArray data = json.getJSONArray("data");

        for (int i = 0; i < data.length(); i++) {
            JSONObject object = data.getJSONObject(i); 

            JSONObject category = object.getJSONObject("Category");

            Category_ID.add(Long.parseLong(category.getString("Category_ID")));
            Category_name.add(category.getString("Category_name"));
            Category_image.add(category.getString("Category_image"));
            Log.d("Category name", Category_name.get(i));

        }

以下是我试图保存文件的代码......

String FILENAME = "somefile";
String string = "hello world!"; 

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

FileInputStream fis = openFileInput(FILENAME);
fis.read(string);
fis.close();

1 个答案:

答案 0 :(得分:0)

您的代码没有任何线索,因为它被fge评论失败的原因和地点。但下面是可以帮助您写入和读取文件的代码。请注意,它将从文件中读取 bytes

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ReadWrite {

    public static void main(String[] args) throws Exception {
        String FILENAME = "data.dat";
        String string = "hello world!";

        FileOutputStream fos = new FileOutputStream(new File(FILENAME)); //openFileOutput(FILENAME); //, Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.close();

        FileInputStream fis = new FileInputStream(new File(FILENAME)); //(FILENAME);
        byte[] b = new byte[100];
        //fis.read(string);
        fis.read(b);
        fis.close();
        System.out.println(b.toString());
    }
}

希望这会有所帮助