Last active
January 2, 2020 10:20
-
-
Save sidward35/cee1b92f6742e5f727a35740f03442b6 to your computer and use it in GitHub Desktop.
Android read/write to file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<manifest> | |
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> | |
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> | |
<application> | |
... | |
</application> | |
</manifest> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void writeToFile(String data) { | |
try { | |
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config", Context.MODE_PRIVATE)); | |
outputStreamWriter.write(data); | |
outputStreamWriter.close(); | |
} | |
catch (IOException e) { | |
Log.e("Exception", "File write failed: " + e.toString()); | |
} | |
} | |
private String readFromFile() { | |
String ret = ""; | |
try { | |
InputStream inputStream = openFileInput("config"); | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment