简体   繁体   English

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

[英]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. 是的,我是一个新手,刚开始学习Java。

Here is my JSON code... 这是我的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));

        }

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. 您的代码不知道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 希望这会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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