简体   繁体   中英

Storing fetched string to a file in Java

I'm trying to save data fetched from a server to a file but I can't get it to work.

Can someone help me? And yes, I'm a newbie, just starting to learn Java.

Here is my JSON code...

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));

        }

And here is the code where I am trying to save a file...

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();

Your code does not have any clue why and where it fails as commented by fge. But below is the code which can help you write to and read from a file. Please note it will read bytes from the file.

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());
    }
}

Hope this will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM