How to read and write from file

JSON

It’s very esay to read and write from a file.

Download code

public static void writeToFile(String data, Activity activity) {
		try {
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
					activity.openFileOutput("config.txt", Context.MODE_PRIVATE));
			outputStreamWriter.write(data);
			outputStreamWriter.close();
		} catch (IOException e) {
			Log.e("Exception", "File write failed: " + e.toString());
		}
	}

	public static String readFromFile(Activity activity) {

		String ret = "";

		try {
			InputStream inputStream = activity.openFileInput("config.txt");

			if (inputStream != null) {
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream);
				BufferedReader bufferedReader = new BufferedReader(
						inputStreamReader);
				String receiveString = "";
				StringBuilder stringBuilder = new StringBuilder();

				while ((receiveString = bufferedReader.readLine()) != null) {
					stringBuilder.append(receiveString);
				}

				inputStream.close();
				ret = stringBuilder.toString();
			}
		} catch (FileNotFoundException e) {
			Log.e("login activity", "File not found: " + e.toString());
		} catch (IOException e) {
			Log.e("login activity", "Can not read file: " + e.toString());
		}
		 return ret;
	}

One thought on “How to read and write from file

  1. Pingback: How to read and write JSON from file with Gson • The Developer World Is Yours

Leave a Reply

Your email address will not be published. Required fields are marked *