Read/Write String from/to a File in Android
Hope this might be useful to you.
Write File:
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Read File:
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.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("\n").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;
}
Write a string to a file
Not having specified a path, your file will be saved in your app space (/data/data/your.app.name/
).
Therefore, you better save your file onto an external storage (which is not necessarily the SD card, it can be the default storage).
You might want to dig into the subject, by reading the official docs
In synthesis:
Add this permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It includes the READ permission, so no need to specify it too.
Save the file in a location you specify (this is taken from my live cod, so I'm sure it works):
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
Environment.DIRECTORY_DCIM + "/YourFolder/"
);
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
[EDIT] OK Try like this (different path - a folder on the external storage):
String path =
Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
// Create the folder.
File folder = new File(path);
folder.mkdirs();
// Create the file.
File file = new File(folder, "config.txt");
Android: Write string to file
OpenFileOutput accepts a filename without separators, as written below
Context | Android Developers
So it would be
Writer writer = null;
try {
writer = new OutputStreamWriter(openFileOutput("url.txt", Context.MODE_PRIVATE));
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) writer.close();
}
For a private directory.
Note that there is no such thing as private mode on an external storage.
It is a bad idea to store configuration files on external storage, because
- The file messes folder structure
- The file will not be deleted with the app nor cleared with data
- The file can be deleted by user or removed if the external storage is removable
- The file can be easily accessed and violated by a user.
So what you probably need is what I've said above, but if you really need to write there, the proper way is listed below
Also I don't like hardcoding separators.
Also, if you need a file on an external storage, proper way of creating a File object is
Writer writer = null;
try {
// get config dir
final File configDir = new File(Environment.getExternalStorageDirectory(), "config");
//make sure it's created
configDir.mkdir();
// open a stream
writer = new OutputStreamWriter(new FileOutputStream(new File(configDir, "url.txt")));
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) writer.close();
}
How to write text to a file on external storage on android?
But is there a way to 'see' the file created with the File Manager on android?
I am not certain what "the File Manager" is that you are referring to, as Android does not really have one. However, you are writing to an app's internal storage, and that is private to the app. It cannot be viewed by other apps or ordinary users, except on rooted devices and via some cumbersome Android SDK tools.
So how to do this right?
File file = new File(this.getExternalFilesDir(null), "testfile.txt");
FileOutputStream fileOutput = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutput);
outputStreamWriter.write("lalala");
outputStreamWriter.flush();
fileOutput.getFD().sync();
outputStreamWriter.close();
Also:
Please do this work on a background thread
On Android 4.3 (API Level 18) and older devices, you need to hold the
WRITE_EXTERNAL_STORAGE
permission to work with external storage
If you also want to have this file show up quickly in on-device or on-development-machine file managers, use this after closing the file:
MediaScannerConnection.scanFile(
this,
new String[]{file.getAbsolutePath()},
null,
null);
(where this
is some Context
, such as an Activity
or Service
)
Android: how to write a file to internal storage
Use the below code to write a file to internal storage:
public void writeFileOnInternalStorage(Context mcoContext, String sFileName, String sBody){
File dir = new File(mcoContext.getFilesDir(), "mydir");
if(!dir.exists()){
dir.mkdir();
}
try {
File gpxfile = new File(dir, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (Exception e){
e.printStackTrace();
}
}
Starting in API 19, you must ask for permission to write to storage.
You can add read and write permissions by adding the following code to AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can prompt the user for read/write permissions using:
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);
and then you can handle the result of the permission request in onRequestPermissionsResult()
inside activity called from it.
write and read strings to/from internal file
Writing strings this way doesn't put any sort of delimiters in the file. You don't know where one string ends and the next starts. That's why you must specify the length of the strings when reading them back.
You can use DataOutputStream.writeUTF()
and DataInputStream.readUTF()
instead as these methods put the length of the strings in the file and read back the right number of characters automatically.
In an Android Context you could do something like this:
try {
// Write 20 Strings
DataOutputStream out =
new DataOutputStream(openFileOutput(FILENAME, Context.MODE_PRIVATE));
for (int i=0; i<20; i++) {
out.writeUTF(Integer.toString(i));
}
out.close();
// Read them back
DataInputStream in = new DataInputStream(openFileInput(FILENAME));
try {
for (;;) {
Log.i("Data Input Sample", in.readUTF());
}
} catch (EOFException e) {
Log.i("Data Input Sample", "End of file reached");
}
in.close();
} catch (IOException e) {
Log.i("Data Input Sample", "I/O Error");
}
Write /Read String Array to File in Android, using internal or external storage whichever is available
here is how i did it.. Thank you guys For Your Help..:)
public static void createDirectory(Context context){
Log.i(TAG,"createDirectory() called...");
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
cacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
Log.i(TAG,"cacheDir exists in ext storage?: "+cacheDir.isDirectory());
}
else{
cacheDir=context.getCacheDir();
Log.i(TAG,"cacheDir exists in int storage?: "+cacheDir.isDirectory());
}
if(!cacheDir.isDirectory()){
cacheDir.mkdirs();
Log.i(TAG,"A New Directory is made[ "+cacheDir.getAbsolutePath());
}
else{
Log.i(TAG,"Cache Dir already exists[ "+cacheDir.getAbsolutePath());
}
}
public static File getFile(String filename){
//String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, String.valueOf(filename.hashCode()));
return f;
}
public static void saveFile(String dataToWrite, File file){
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
outputStreamWriter.write(dataToWrite);
outputStreamWriter.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
public static String readFromFile(File file){
try{
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
bufferedReader.close();
inputStreamReader.close();
return stringBuilder.toString();
}
catch (FileNotFoundException e) {
} catch (IOException e) {
}
return null;
}
Related Topics
Download a File With Android, and Showing the Progress in a Progressdialog
How to Redirect Multiple Types of Users to Their Respective Activities
Base 64 Encode and Decode Example Code
Gradle Finds Wrong Java_Home Even Though It's Correctly Set
Calculating the Difference Between Two Java Date Instances
Difference Between "Text" and New String("Text")
How to Concatenate Two Arrays in Java
Why Is a Concurrentmodificationexception Thrown and How to Debug It
How to Read the Value of a Private Field from a Different Class in Java
Android Update 17 Seems Incompatible With External Jars
How to Change the Decimal Separator of Decimalformat from Comma to Dot/Point
Do Line Endings Differ Between Windows and Linux
What Issues Should Be Considered When Overriding Equals and Hashcode in Java
How to Import the Javax.Servlet/Jakarta.Servlet API in My Eclipse Project