java Save files on device storage Android Read Write External Storage File Example
Monday, December 31, 2018

java Save files on device storage Android Read Write External Storage File Example

Android DevelopersAndroid Developers

  • Documentation

"dimension8": null, "gaid": "UA-49880327-2"”>

Save files on device storage

Android uses a file system that’s
similar to disk-based file systems on other platforms. This page describes
how to work with the Android file system to read and write files with the File
APIs.

A File object works well for reading or writing large amounts of data in
start-to-finish order without skipping around. For example, it’s good for image files or
anything exchanged over a network.

The exact location of the where your files can be saved
might vary across devices, so you should use the methods described on this page to access
internal and external storage paths instead of using absolute file paths.

To view files on a device, you can log the file location provided by methods such as
File.getAbsolutePath() , and then browse the device files
with Android Studio’s Device File Explorer .

Choose internal or external storage

All Android devices have two file storage areas: “internal” and “external” storage. These names
come from the early days of Android, when most devices offered built-in non-volatile memory
(internal storage), plus a removable storage medium such as a micro SD card (external storage).
Many devices now divide the permanent storage space into separate “internal” and “external”
partitions. So even without a removable storage medium, these two storage spaces always exist, and
the API behavior is the same regardless of whether the external storage is removable.

Because the external storage might be removable, there are some differences between these
two options as follows.

Internal storage:

  • It’s always available.
  • Files saved here are accessible by only your app.
  • When the user uninstalls your app, the system removes all your app’s files from
    internal storage.

Internal storage is best when you want to be sure that neither the user nor other apps can
access your files.

External storage:

  • It’s not always available, because the user can mount the external storage as USB storage
    and in some cases remove it from the device.
  • It’s world-readable, so
    files saved here may be read outside of your control.
  • When the user uninstalls your app, the system removes your app’s files from here
    only if you save them in the directory from getExternalFilesDir() .

External storage is the best
place for files that don’t require access restrictions and for files that you want to share
with other apps or allow the user to access with a computer.

Tip: Although apps are installed onto the internal storage by
default, you can allow your app to be installed on external storage by specifying the
android:installLocation
attribute in your manifest. Users appreciate this option when the APK size is very large and
they have an external storage space that’s larger than the internal storage. For more
information, see App Install Location .

Save a file on internal storage

Your app’s internal storage directory is specified
by your app’s package name in a special location of the Android file system that can be
accessed with the following APIs.

Note: Unlike the external storage
directories , your app does not require any system permissions to read and write to the internal
directories returned by these methods.

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a
File by calling one of two methods:

getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()
Returns a File representing an internal directory for your app’s temporary
cache files. Be sure to delete each file once it is no
longer needed and implement a reasonable size limit for the amount of memory you use at any given
time, such as 1MB.

Caution:
If the system runs low on storage, it may delete your cache files without warning.

To create a new file in one of these directories, you can use the File() constructor, passing the File provided by one
of the above methods that specifies your internal storage directory. For example:

Kotlin

val file = File(context.filesDir, filename)

Java

File file = new File(context.getFilesDir(), filename);

Alternatively, you can call openFileOutput() to get a FileOutputStream
that writes to a file in your internal directory. For example, here’s
how to write some text to a file:

Kotlin

val filename = "myfile"
val fileContents = "Hello world!"
context.openFileOutput(filename, Context.MODE_PRIVATE).use it.write(fileContents.toByteArray())

Java

String filename = "myfile";
String fileContents = "Hello world!";
FileOutputStream outputStream;
try outputStream = openFileOutput(filename, Context.MODE_PRIVATE); outputStream.write(fileContents.getBytes()); outputStream.close(); catch (Exception e) e.printStackTrace();

Notice that the openFileOutput() method
requires a file mode parameter. Passing
MODE_PRIVATE makes it private to your app.
The other mode options, MODE_WORLD_READABLE and
MODE_WORLD_WRITEABLE , have been deprecated since API level 17.
Starting with Android 7.0 (API level 24), Android throws a
SecurityException if you use them. If your app needs to share private
files with other apps, you should instead use a FileProvider with
the FLAG_GRANT_READ_URI_PERMISSION .
For more information, see Sharing Files .

On Android 6.0 (API level 23) and lower, other apps can read your internal files if
you set the file mode to be world readable. However, the other app must know your app
package name and file names. Other apps cannot browse your internal directories and do not have read
or write access unless you explicitly set the files to be readable or writable. So as long as you
use MODE_PRIVATE for your files on the internal storage, they are
never accessible to other apps.

Write a cache file

If you instead need to cache some files, you should use
createTempFile() . For example, the following method extracts the
file name from a URL and creates a file with that name
in your app’s internal cache directory:

Kotlin

private fun getTempFile(context: Context, url: String): File? = Uri.parse(url)?.lastPathSegment?.let filename -> File.createTempFile(filename, null, context.cacheDir) 

Java

private File getTempFile(Context context, String url) File file; try String fileName = Uri.parse(url).getLastPathSegment(); file = File.createTempFile(fileName, null, context.getCacheDir()); catch (IOException e) // Error while creating file return file;

Files created with createTempFile() are placed in a cache
directory that’s private to your app. You should regularly delete the
files you no longer need.

Caution:
If the system runs low on storage, it may delete your cache files without warning,
so make sure you check for the existence of your cache files before reading them.

Open an existing file

To read an existing file, call openFileInput(name) , passing the name of the file.

You can get an array of all your app’s file names by calling
fileList() .

Tip: If you need to package a file in your app that is accessible at
install time, save the file in your project’s res/raw/ directory. You can open these
files with openRawResource() ,
passing the R.raw.filename resource ID. This
method returns an InputStream that you can use to read the file.
You cannot write to the original file.

Open a directory

You can open a directory on the internal file system with the following methods:

getFilesDir()
Returns a File representing the directory on the file system that’s
uniquely associated with your app.
getDir(name, mode)
Creates a new directory (or opens an existing directory)
within your app’s unique file system directory. This new directory appears inside the directory
provided by getFilesDir() .
getCacheDir()
Returns a File representing the cache directory on the file system that’s
uniquely associated with your app. This directory is meant for temporary files, and it should
be cleaned up regularly. The system may delete files there if it runs low on disk space, so
make sure you check for the existence of your cache files before reading them.

To create a new file in one of these directories, you can use the
File() constructor, passing the File object
provided by one of the above methods that specifies your internal storage directory. For
example:

Kotlin

val directory = context.filesDir
val file = File(directory, filename)

Java

File directory = context.getFilesDir();
File file = new File(directory, filename);

Save a file on external storage

Using the external storage is great for files that you want
to share with other apps or allow the user to access with a computer.

After you request storage permissions and verify that storage is available , you can save two different types
of files:

  • Public files : Files that
    should be freely available to other apps and to the user. When the user uninstalls your app,
    these files should remain available to the user. For example, photos captured by your app or other
    downloaded files should be saved as public files.
  • Private files :
    Files that rightfully belong to your app and will be deleted when the user uninstalls
    your app. Although these files are technically accessible by the user and other apps because they
    are on the external storage, they don’t provide value to the user
    outside of your app.

Caution: The external storage might become unavailable if the user
removes the SD card or connects the device to a computer. And the files are still visible to the
user and other apps that have the READ_EXTERNAL_STORAGE
permission. So if your app’s functionality depends on these
files or you need to completely restrict access, you
should instead write your files to the internal storage .

Request external storage permissions

To write to the public external storage, you must request the
WRITE_EXTERNAL_STORAGE permission in your manifest file :

<manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ...
</manifest>

Note:
If your app uses the WRITE_EXTERNAL_STORAGE
permission, then it implicitly has permission to read the external storage as well.

If your app only needs
to read the external storage (but not write to it), then you need to declare the
READ_EXTERNAL_STORAGE permission:

<manifest ...> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ...
</manifest>

Beginning with Android 4.4 (API level 19), reading or writing files in your app’s private
external storage directory—accessed using
getExternalFilesDir() —does not require
the READ_EXTERNAL_STORAGE
or WRITE_EXTERNAL_STORAGE
permissions. So if your app supports Android 4.3 (API level 18) and lower, and you want to access
only the private external storage directory, you should declare that the permission
be requested only on the lower versions of Android by adding the
maxSdkVersion
attribute:

<manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" /> ...
</manifest>

Verify that external storage is available

Because the external storage might be unavailable—such as when the user has mounted the
storage to a PC or has removed the SD card that provides the external storage—you
should always verify that the volume is available before accessing it. You can query the external
storage state by calling getExternalStorageState() . If the returned
state is MEDIA_MOUNTED , then you can read and
write your files. If it’s MEDIA_MOUNTED_READ_ONLY , you can only
read the files.

For example, the following methods are useful to determine the storage
availability:

Kotlin

fun isExternalStorageWritable(): Boolean return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
fun isExternalStorageReadable(): Boolean return Environment.getExternalStorageState() in setOf(Environment.MEDIA_MOUNTED, Environment.MEDIA_MOUNTED_READ_ONLY)

Java

public boolean isExternalStorageWritable() String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) return true; return false;
public boolean isExternalStorageReadable() Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) return true; return false;

Save to a public directory

If you want to save public files on the external storage, use the
getExternalStoragePublicDirectory() method to get a File representing
the appropriate directory on the external storage. The method takes an argument specifying
the type of file you want to save so that they can be logically organized with other public
files, such as DIRECTORY_MUSIC or
DIRECTORY_PICTURES . For example:

Kotlin

fun getPublicAlbumStorageDir(albumName: String): File? // Get the directory for the user's public pictures directory. val file = File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), albumName) if (!file?.mkdirs()) Log.e(LOG_TAG, "Directory not created") return file

Java

public File getPublicAlbumStorageDir(String albumName) // Get the directory for the user's public pictures directory. File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), albumName); if (!file.mkdirs()) Log.e(LOG_TAG, "Directory not created"); return file;

If you want to hide your files from the Media Scanner, include an empty file named
.nomedia in your external files directory (note the dot
prefix in the filename). This prevents media scanner from reading your media
files and providing them to other apps through the MediaStore
content provider.

Save to a private directory

If you want to save files on external storage that are private to your app and not
accessible by the MediaStore content provider, you can acquire a
directory that’s used by only your app by calling
getExternalFilesDir() and passing it a name
indicating the type of directory you’d like. Each directory created this way is added to a parent
directory that encapsulates all your app’s external storage files, which the system deletes when the
user uninstalls your app.

Caution: Files on external storage are not always accessible, because
users can mount the external storage to a computer for use as a storage device. So if you need to
store files that are critical to your app’s functionality, you should instead store them on
internal storage .

For example, here’s a method you can use to create a directory for an individual photo album:

Kotlin

fun getPrivateAlbumStorageDir(context: Context, albumName: String): File? // Get the directory for the app's private pictures directory. val file = File(context.getExternalFilesDir( Environment.DIRECTORY_PICTURES), albumName) if (!file?.mkdirs()) Log.e(LOG_TAG, "Directory not created") return file

Java

public File getPrivateAlbumStorageDir(Context context, String albumName) // Get the directory for the app's private pictures directory. File file = new File(context.getExternalFilesDir( Environment.DIRECTORY_PICTURES), albumName); if (!file.mkdirs()) Log.e(LOG_TAG, "Directory not created"); return file;

If none of the pre-defined sub-directory names suit your files, you can instead call
getExternalFilesDir() and pass
null. This returns the root directory for your app’s private directory on the external
storage.

Remember that getExternalFilesDir()
creates a directory that is deleted when the user uninstalls your app.
If the files you’re saving should remain available after the user uninstalls your
app—such as when your app captures photos and the user should keep those photos—you
should instead save the files to a public directory .

Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared or
getExternalFilesDir() for files that are private to your app, it’s important that you use
directory names provided by API constants like
DIRECTORY_PICTURES . These directory names ensure
that the files are treated properly by the system. For instance, files saved in
DIRECTORY_RINGTONES are categorized by the system media scanner as
ringtones instead of music.

Select between multiple storage locations

Sometimes, a device that allocates a partition of the
internal memory for use as the external storage also provides an SD card slot.
This means that the device has two different external storage directories, so you need to select
which one to use when writing “private” files to the external storage.

Beginning with Android 4.4 (API level 19), you can access both locations by calling
getExternalFilesDirs() , which returns
a File array with entries for each storage location. The first entry in the array
is considered the primary external storage, and you should use that location unless it’s full or
unavailable.

If your app supports Android 4.3 and lower, you should use the support library’s
static method, ContextCompat.getExternalFilesDirs() . This always returns a File array, but if the
device is running Android 4.3 and lower, then it contains just one entry for the primary
external storage (if there’s a second storage location, you cannot access it on Android 4.3 and
lower).

Query free space

If you know ahead of time how much data you’re saving, you can find out
whether sufficient space is available without causing an IOException by calling
getFreeSpace() or getTotalSpace() . These methods provide the
current available space and the
total space in the storage volume, respectively. This information is also useful to avoid filling
the storage volume above a certain threshold.

However, the system does not guarantee that you can write as many bytes as are
indicated by getFreeSpace() . If the number returned is a
few MB more than the size of the data you want to save, or if the file system
is less than 90% full, then it’s okay to proceed.
Otherwise, you probably shouldn’t write to storage.

Note: You aren’t required to check the amount of available space
before you save your file. You can instead try writing the file right away, then
catch an IOException if one occurs. You may need to do
this if you don’t know exactly how much space you need. For example, if you
change the file’s encoding before you save it by converting a PNG image to
JPEG, you won’t know the file’s size beforehand.

Delete a file

You should always delete files that your app no longer need. The most straightforward way to
delete a file is to call delete() on the File object.

Kotlin

myFile.delete()

Java

myFile.delete();

If the file is saved on internal storage, you can also ask the Context
to locate and delete a file by calling deleteFile() :

Kotlin

myContext.deleteFile(fileName)

Java

myContext.deleteFile(fileName);

Note: When the user uninstalls your app, the Android system deletes
the following:

  • All files you saved on internal storage.
  • All files you saved external storage using getExternalFilesDir() .

However, you should manually delete all cached files created with
getCacheDir() on a regular basis and also regularly delete
other files you no longer need.

Content and code samples on this page are subject to the licenses described in the Content License . Java is a registered trademark of Oracle and/or its affiliates.

Last updated April 25, 2018.

Stack Overflow



  1. Log In
    Sign Up

  2. current community


    • Stack Overflow

      help
      chat

    • Meta Stack Overflow

    your communities

    Sign up or log in to customize your list.

    more stack exchange communities

    company blog

    • Tour

      Start here for a quick overview of the site

    • Help Center

      Detailed answers to any questions you might have

    • Meta

      Discuss the workings and policies of this site

    • About Us

      Learn more about Stack Overflow the company

    • Business

      Learn more about hiring developers or posting ads with us

By using our site, you acknowledge that you have read and understand our Cookie Policy , Privacy Policy , and our Terms of Service .

How to Read/Write String from a File in Android

Ask Question


up vote
150
down vote

favorite

75

I want to save a file to the internal storage by getting the text inputted from EditText. Then I want the same file to return the inputted text in String form and save it to another String which is to be used later.

Here’s the code:

package com.omm.easybalancerecharge;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText num = (EditText) findViewById(R.id.sNum); Button ch = (Button) findViewById(R.id.rButton); TelephonyManager operator = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String opname = operator.getNetworkOperatorName(); TextView status = (TextView) findViewById(R.id.setStatus); final EditText ID = (EditText) findViewById(R.id.IQID); Button save = (Button) findViewById(R.id.sButton); final String myID = ""; //When Reading The File Back, I Need To Store It In This String For Later Use save.setOnClickListener(new OnClickListener() @Override public void onClick(View v) // TODO Auto-generated method stub //Get Text From EditText "ID" And Save It To Internal Memory ); if (opname.contentEquals("zain SA")) status.setText("Your Network Is: " + opname); else status.setText("No Network"); ch.setOnClickListener(new OnClickListener() @Override public void onClick(View v) // TODO Auto-generated method stub //Read From The Saved File Here And Append It To String "myID" String hash = Uri.encode("#"); Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:*141*" + num.getText() + hash)); startActivity(intent); ); 

I have included comments to help you further analyze my points as to where I want the operations to be done/variables to be used.

java android string file-io

share | improve this question

edited Sep 26 at 1:28

Cœur

17.2k9102142

asked Jan 17 ’13 at 10:20

Major Aly

7922714

  • 1

    the question is "how to read/write to/from file?"
    –  Dmitri Gudkov
    Jan 17 ’13 at 10:22

  • Did you consider using the app’s preferences to store your strings ?
    –  fiddler
    Jan 17 ’13 at 10:23

  • 4

    BTW, be sure you put permission to the mainfest file, to operate with storage…
    –  Dmitri Gudkov
    Jan 17 ’13 at 10:24

  • This is my half complete app with many changes to implement. My idea is that the user enter the ID only once at the first run of the app. Then the app will reference that stored ID as many times as the user runs the app. Permissions are all added to the manifest.
    –  Major Aly
    Jan 17 ’13 at 10:28


add a comment  | 

7 Answers
7

active

oldest

votes


up vote
280
down vote

accepted

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

share | improve this answer

edited Aug 10 ’16 at 13:59

VSB

3,94153981

answered Jan 17 ’13 at 10:39

R9J

4,77541323

  • 40

    If the class is not extended from Activity, usage of the "openFileInput()" method should be like this: context.openFileInput()
    –  Behzad
    Oct 21 ’13 at 10:17

  • 9

    Note: The code above works well, but the resulting String will not contain any of the linebreaks from the file. To add linebreaks again, change line "stringBuilder.append(receiveString);" to "stringBuilder.append(receiveString).append("\n");". If you expect other linebreak characters (e.g. Windows text files will have \r etc..), in your final string, you’ll have to adapt this a bit more.
    –  treesAreEverywhere
    Feb 9 ’14 at 23:57

  • 16

    where this config file saves in real device? i could not find it to check 🙁
    –  Kenji
    Oct 29 ’14 at 6:58

  • 4

    I think, closing streams should be in the final block as in @SharkAlley answer
    –  Yurii K
    Jul 29 ’15 at 14:41

  • 2

    @saganaut – I was talking about finally block: finally inputStream.close();. And for finalizers – it’s true, you can’t rely on them to close resources
    –  Yurii K
    Sep 7 ’16 at 15:03

 | 
show 7 more comments


up vote
147
down vote

For those looking for a general strategy for reading and writing a string to file:

First, get a file object

You’ll need the storage path. For the internal storage, use:

File path = context.getFilesDir();

For the external storage (SD card), use:

File path = context.getExternalFilesDir(null);

Then create your file object:

File file = new File(path, "my-file-name.txt");

Write a string to the file

FileOutputStream stream = new FileOutputStream(file);
try stream.write("text-to-write".getBytes()); finally stream.close();

Or with Google Guava

String contents = Files.toString(file, StandardCharsets.UTF_8);

Read the file to a string

int length = (int) file.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(file);
try in.read(bytes); finally in.close();
String contents = new String(bytes); 

Or if you are using Google Guava

String contents = Files.toString(file,"UTF-8");

For completeness I’ll mention

String contents = new Scanner(file).useDelimiter("\\A").next();

which requires no libraries, but benchmarks 50% – 400% slower than the other options (in various tests on my Nexus 5).

Notes

For each of these strategies, you’ll be asked to catch an IOException.

The default character encoding on Android is UTF-8.

If you are using external storage, you’ll need to add to your manifest either:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

or

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Write permission implies read permission, so you don’t need both.

share | improve this answer

edited Dec 18 ’17 at 17:50

Ulala

34

answered Feb 28 ’14 at 10:48

SharkAlley

8,31144240

  • Ok for example I want a user to see all his posts, and when he goes to another screen and comes back, do I need to draw it again or because it is cached it just pulls it out from cache and just shows it, if it just does pull it out, how do I add an if conditional to say not to query my servers
    –  Lion789
    Mar 8 ’14 at 5:55

  • 2

    Don’t do it like new File(path + "/my-file-name.txt");. This defies much of the sense of File. Use new File(path, "my-file-name.txt"); instead.
    –  JimmyB
    Aug 10 ’15 at 9:13

  • @HannoBinder Android always runs on top of Linux, so the separator is guaranteed to be "/". What would be the benefit of using new File(path, "my-file-name.txt") in this context? (I’m happy to update the answer if there is a reason to.)
    –  SharkAlley
    Aug 11 ’15 at 20:05


  • 1

    File is there for a reason. In your case, you could just as well skip File and just do new FileInputStream(path + "/my-file-name.txt");, which I don’t recommend. (What if path contains a trailing / for example?)
    –  JimmyB
    Aug 12 ’15 at 14:28


  • Edited per your suggestion. Thanks 🙂
    –  SharkAlley
    Aug 21 ’15 at 17:20

 | 
show 1 more comment


up vote
28
down vote

public static void writeStringAsFile(final String fileContents, String fileName) Context context = App.instance.getApplicationContext(); try FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName)); out.write(fileContents); out.close(); catch (IOException e) Logger.logError(TAG, e);
public static String readFileAsString(String fileName) Context context = App.instance.getApplicationContext(); StringBuilder stringBuilder = new StringBuilder(); String line; BufferedReader in = null; try in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName))); while ((line = in.readLine()) != null) stringBuilder.append(line); catch (FileNotFoundException e) Logger.logError(TAG, e); catch (IOException e) Logger.logError(TAG, e); return stringBuilder.toString();

share | improve this answer

edited Apr 14 at 13:58

NathanWindisch

175

answered Jul 23 ’13 at 15:08

Eugene

24.1k71196309

  • 6

    App !? what does it supposed to be !?
    –  alap
    Jun 8 ’14 at 19:26


  • @alap Is something @Eugene is using to retrieve app context statically. He need it for context.getFilesDir(). You can just replace occurrences of new File(context.getFilesDir(), fileName) with a File object or a String passed to function instead of fileName.
    –  lorenzo-s
    Feb 17 ’15 at 9:06


add a comment  | 


up vote
7
down vote

Just a a bit modifications on reading string from a file method for more performance

private String readFromFile(Context context, String fileName) if (context == null) return null; String ret = ""; try InputStream inputStream = context.openFileInput(fileName); if ( inputStream != null ) InputStreamReader inputStreamReader = new InputStreamReader(inputStream); int size = inputStream.available(); char[] buffer = new char[size]; inputStreamReader.read(buffer); inputStream.close(); ret = new String(buffer); catch (Exception e) e.printStackTrace(); return ret;

share | improve this answer

answered Dec 16 ’14 at 6:18

Tai Le Anh

20927

add a comment  | 


up vote
5
down vote

check the below code.

Reading from a file in the filesystem.

FileInputStream fis = null; try { fis = context.openFileInput(fileName); InputStreamReader isr = new InputStreamReader(fis); // READ STRING OF UNKNOWN LENGTH StringBuilder sb = new StringBuilder(); char[] inputBuffer = new char[2048]; int l; // FILL BUFFER WITH DATA while ((l = isr.read(inputBuffer)) != -1) sb.append(inputBuffer, 0, l); // CONVERT BYTES TO STRING String readString = sb.toString(); fis.close(); catch (Exception e) finally if (fis != null) fis = null; 

below code is to write the file in to internal filesystem.

FileOutputStream fos = null; try fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); fos.write(stringdatatobestoredinfile.getBytes()); fos.flush(); fos.close(); catch (Exception e) finally if (fos != null) fos = null; 

I think this will help you.

share | improve this answer

answered Jan 17 ’13 at 10:28

Raj

1,50911942

add a comment  | 


up vote
3
down vote

I’m a bit of a beginner and struggled getting this to work today.

Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!

public class HighScore File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator); File file = new File(data, "highscore.txt"); private int highScore = 0; public int readHighScore() try BufferedReader br = new BufferedReader(new FileReader(file)); try highScore = Integer.parseInt(br.readLine()); br.close(); catch (NumberFormatException catch (FileNotFoundException e) try file.createNewFile(); catch (IOException ioe) ioe.printStackTrace(); e.printStackTrace(); return highScore; public void writeHighScore(int highestScore) try BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(String.valueOf(highestScore)); bw.close(); catch (IOException e) e.printStackTrace(); 

share | improve this answer

answered May 10 ’16 at 7:53

Nihilarian

313

add a comment  | 


up vote
-1
down vote

To append an existing file.

 File file = new File(persistPath); BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024); out.write(str); out.newLine(); out.close(); 

share | improve this answer

answered Feb 17 ’16 at 8:13

kakopappa

3,25234168

add a comment  | 

protected by Community Sep 1 ’16 at 23:09

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count ).

Would you like to answer one of these unanswered questions instead?

Not the answer you’re looking for? Browse other questions tagged java android string file-io or ask your own question .

asked

5 years, 10 months ago

viewed

392,191 times

active

2 months ago

Linked

-1

How to create and write data a text file in android programatically?

-3

Save text/string internally Android

21

Write a string to a file

5

How to Cache Json data to be available offline?

4

ANDROID: How to save JSON data in a file and retrieve it?

2

How to write text to a file on external storage on android?

2

Save String as html file android

3

How to access /data folder of another application through your application?

1

saving JSON file from url in Internal Storage

0

Android: read large text file

see more linked questions…

Related

3428

How to read / convert an InputStream into a String in Java?

1292

How do I create a Java string from the contents of a file?

2694

How do I tell if a regular file does not exist in Bash?

3140

How do I make the first letter of a string uppercase in JavaScript?

3418

How to replace all occurrences of a string in JavaScript

3176

Why is the Android emulator so slow? How can we speed up the Android emulator?

7435

How to check whether a string contains a substring in JavaScript?

1204

How do I create a file and write to it in Java?

2667

How do I check if a string contains a specific word?

2668

How do I convert a String to an int in Java?

Hot Network Questions

  • Why is it possible to flip the screen?

  • Should I tell my coworkers I was asked to leave?

  • How do microstrips actually represent lumped components?

  • What would be the necessary conditions to rain bubbles?

  • Does a client certificate identify the owner to unrelated websites?

  • Close all tabs in Safari except for one

  • Garlic press with minimum force required

  • Was Japan known to be a potential threat to the USA in the 10 year period prior to 1941

  • Combining first two letters from first name and first two letters from last name

  • Would it be more efficient to build fleets in orbit?

  • MOSFET W/L ratio limits: what’s (un)reasonable?

  • Do industry professionals building games using UE4 use Blueprints at all, or do they use C++ exclusively?

  • Why are the blueprints of old satellites still not available to public?

  • Is it possible to buy round-trip tickets to Jamaica where the return ticket is counterfeit?

  • A function to fill in a column with NA of the same type

  • What should I choose, Life or Nirvana?

  • How honest should I be in disclosing not-so-exciting results?

  • What to teach after scales and chords

  • Manipulating text in first column only?

  • What is a word for ascribing divine characteristics to a machine?

  • My cat is not eating anything after the death of the fellow cat

  • What if a law is literally impossible to follow?

  • Book about old man storing magical power into plates

  • Using private software at work

more hot questions


question feed

lang-java

Stack Overflow works best with JavaScript enabled

Stack Overflow



  1. Log In
    Sign Up

  2. current community


    • Stack Overflow

      help
      chat

    • Meta Stack Overflow

    your communities

    Sign up or log in to customize your list.

    more stack exchange communities

    company blog

    • Tour

      Start here for a quick overview of the site

    • Help Center

      Detailed answers to any questions you might have

    • Meta

      Discuss the workings and policies of this site

    • About Us

      Learn more about Stack Overflow the company

    • Business

      Learn more about hiring developers or posting ads with us

By using our site, you acknowledge that you have read and understand our Cookie Policy , Privacy Policy , and our Terms of Service .

How to Read/Write String from a File in Android

Ask Question


up vote
150
down vote

favorite

75

I want to save a file to the internal storage by getting the text inputted from EditText. Then I want the same file to return the inputted text in String form and save it to another String which is to be used later.

Here’s the code:

package com.omm.easybalancerecharge;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText num = (EditText) findViewById(R.id.sNum); Button ch = (Button) findViewById(R.id.rButton); TelephonyManager operator = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String opname = operator.getNetworkOperatorName(); TextView status = (TextView) findViewById(R.id.setStatus); final EditText ID = (EditText) findViewById(R.id.IQID); Button save = (Button) findViewById(R.id.sButton); final String myID = ""; //When Reading The File Back, I Need To Store It In This String For Later Use save.setOnClickListener(new OnClickListener() @Override public void onClick(View v) // TODO Auto-generated method stub //Get Text From EditText "ID" And Save It To Internal Memory ); if (opname.contentEquals("zain SA")) status.setText("Your Network Is: " + opname); else status.setText("No Network"); ch.setOnClickListener(new OnClickListener() @Override public void onClick(View v) // TODO Auto-generated method stub //Read From The Saved File Here And Append It To String "myID" String hash = Uri.encode("#"); Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:*141*" + num.getText() + hash)); startActivity(intent); ); 

I have included comments to help you further analyze my points as to where I want the operations to be done/variables to be used.

java android string file-io

share | improve this question

edited Sep 26 at 1:28

Cœur

17.2k9102142

asked Jan 17 ’13 at 10:20

Major Aly

7922714

  • 1

    the question is "how to read/write to/from file?"
    –  Dmitri Gudkov
    Jan 17 ’13 at 10:22

  • Did you consider using the app’s preferences to store your strings ?
    –  fiddler
    Jan 17 ’13 at 10:23

  • 4

    BTW, be sure you put permission to the mainfest file, to operate with storage…
    –  Dmitri Gudkov
    Jan 17 ’13 at 10:24

  • This is my half complete app with many changes to implement. My idea is that the user enter the ID only once at the first run of the app. Then the app will reference that stored ID as many times as the user runs the app. Permissions are all added to the manifest.
    –  Major Aly
    Jan 17 ’13 at 10:28


add a comment  | 

7 Answers
7

active

oldest

votes


up vote
280
down vote

accepted

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

share | improve this answer

edited Aug 10 ’16 at 13:59

VSB

3,94153981

answered Jan 17 ’13 at 10:39

R9J

4,77541323

  • 40

    If the class is not extended from Activity, usage of the "openFileInput()" method should be like this: context.openFileInput()
    –  Behzad
    Oct 21 ’13 at 10:17

  • 9

    Note: The code above works well, but the resulting String will not contain any of the linebreaks from the file. To add linebreaks again, change line "stringBuilder.append(receiveString);" to "stringBuilder.append(receiveString).append("\n");". If you expect other linebreak characters (e.g. Windows text files will have \r etc..), in your final string, you’ll have to adapt this a bit more.
    –  treesAreEverywhere
    Feb 9 ’14 at 23:57

  • 16

    where this config file saves in real device? i could not find it to check 🙁
    –  Kenji
    Oct 29 ’14 at 6:58

  • 4

    I think, closing streams should be in the final block as in @SharkAlley answer
    –  Yurii K
    Jul 29 ’15 at 14:41

  • 2

    @saganaut – I was talking about finally block: finally inputStream.close();. And for finalizers – it’s true, you can’t rely on them to close resources
    –  Yurii K
    Sep 7 ’16 at 15:03

 | 
show 7 more comments


up vote
147
down vote

For those looking for a general strategy for reading and writing a string to file:

First, get a file object

You’ll need the storage path. For the internal storage, use:

File path = context.getFilesDir();

For the external storage (SD card), use:

File path = context.getExternalFilesDir(null);

Then create your file object:

File file = new File(path, "my-file-name.txt");

Write a string to the file

FileOutputStream stream = new FileOutputStream(file);
try stream.write("text-to-write".getBytes()); finally stream.close();

Or with Google Guava

String contents = Files.toString(file, StandardCharsets.UTF_8);

Read the file to a string

int length = (int) file.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(file);
try in.read(bytes); finally in.close();
String contents = new String(bytes); 

Or if you are using Google Guava

String contents = Files.toString(file,"UTF-8");

For completeness I’ll mention

String contents = new Scanner(file).useDelimiter("\\A").next();

which requires no libraries, but benchmarks 50% – 400% slower than the other options (in various tests on my Nexus 5).

Notes

For each of these strategies, you’ll be asked to catch an IOException.

The default character encoding on Android is UTF-8.

If you are using external storage, you’ll need to add to your manifest either:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

or

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Write permission implies read permission, so you don’t need both.

share | improve this answer

edited Dec 18 ’17 at 17:50

Ulala

34

answered Feb 28 ’14 at 10:48

SharkAlley

8,31144240

  • Ok for example I want a user to see all his posts, and when he goes to another screen and comes back, do I need to draw it again or because it is cached it just pulls it out from cache and just shows it, if it just does pull it out, how do I add an if conditional to say not to query my servers
    –  Lion789
    Mar 8 ’14 at 5:55

  • 2

    Don’t do it like new File(path + "/my-file-name.txt");. This defies much of the sense of File. Use new File(path, "my-file-name.txt"); instead.
    –  JimmyB
    Aug 10 ’15 at 9:13

  • @HannoBinder Android always runs on top of Linux, so the separator is guaranteed to be "/". What would be the benefit of using new File(path, "my-file-name.txt") in this context? (I’m happy to update the answer if there is a reason to.)
    –  SharkAlley
    Aug 11 ’15 at 20:05


  • 1

    File is there for a reason. In your case, you could just as well skip File and just do new FileInputStream(path + "/my-file-name.txt");, which I don’t recommend. (What if path contains a trailing / for example?)
    –  JimmyB
    Aug 12 ’15 at 14:28


  • Edited per your suggestion. Thanks 🙂
    –  SharkAlley
    Aug 21 ’15 at 17:20

 | 
show 1 more comment


up vote
28
down vote

public static void writeStringAsFile(final String fileContents, String fileName) Context context = App.instance.getApplicationContext(); try FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName)); out.write(fileContents); out.close(); catch (IOException e) Logger.logError(TAG, e);
public static String readFileAsString(String fileName) Context context = App.instance.getApplicationContext(); StringBuilder stringBuilder = new StringBuilder(); String line; BufferedReader in = null; try in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName))); while ((line = in.readLine()) != null) stringBuilder.append(line); catch (FileNotFoundException e) Logger.logError(TAG, e); catch (IOException e) Logger.logError(TAG, e); return stringBuilder.toString();

share | improve this answer

edited Apr 14 at 13:58

NathanWindisch

175

answered Jul 23 ’13 at 15:08

Eugene

24.1k71196309

  • 6

    App !? what does it supposed to be !?
    –  alap
    Jun 8 ’14 at 19:26


  • @alap Is something @Eugene is using to retrieve app context statically. He need it for context.getFilesDir(). You can just replace occurrences of new File(context.getFilesDir(), fileName) with a File object or a String passed to function instead of fileName.
    –  lorenzo-s
    Feb 17 ’15 at 9:06


add a comment  | 


up vote
7
down vote

Just a a bit modifications on reading string from a file method for more performance

private String readFromFile(Context context, String fileName) if (context == null) return null; String ret = ""; try InputStream inputStream = context.openFileInput(fileName); if ( inputStream != null ) InputStreamReader inputStreamReader = new InputStreamReader(inputStream); int size = inputStream.available(); char[] buffer = new char[size]; inputStreamReader.read(buffer); inputStream.close(); ret = new String(buffer); catch (Exception e) e.printStackTrace(); return ret;

share | improve this answer

answered Dec 16 ’14 at 6:18

Tai Le Anh

20927

add a comment  | 


up vote
5
down vote

check the below code.

Reading from a file in the filesystem.

FileInputStream fis = null; try { fis = context.openFileInput(fileName); InputStreamReader isr = new InputStreamReader(fis); // READ STRING OF UNKNOWN LENGTH StringBuilder sb = new StringBuilder(); char[] inputBuffer = new char[2048]; int l; // FILL BUFFER WITH DATA while ((l = isr.read(inputBuffer)) != -1) sb.append(inputBuffer, 0, l); // CONVERT BYTES TO STRING String readString = sb.toString(); fis.close(); catch (Exception e) finally if (fis != null) fis = null; 

below code is to write the file in to internal filesystem.

FileOutputStream fos = null; try fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); fos.write(stringdatatobestoredinfile.getBytes()); fos.flush(); fos.close(); catch (Exception e) finally if (fos != null) fos = null; 

I think this will help you.

share | improve this answer

answered Jan 17 ’13 at 10:28

Raj

1,50911942

add a comment  | 


up vote
3
down vote

I’m a bit of a beginner and struggled getting this to work today.

Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!

public class HighScore File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator); File file = new File(data, "highscore.txt"); private int highScore = 0; public int readHighScore() try IOException e) e.printStackTrace(); catch (FileNotFoundException e) try file.createNewFile(); catch (IOException ioe) ioe.printStackTrace(); e.printStackTrace(); return highScore; public void writeHighScore(int highestScore) try BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(String.valueOf(highestScore)); bw.close(); catch (IOException e) e.printStackTrace(); 

share | improve this answer

answered May 10 ’16 at 7:53

Nihilarian

313

add a comment  | 


up vote
-1
down vote

To append an existing file.

 File file = new File(persistPath); BufferedWriter out = new BufferedWriter(new FileWriter(file, true), 1024); out.write(str); out.newLine(); out.close(); 

share | improve this answer

answered Feb 17 ’16 at 8:13

kakopappa

3,25234168

add a comment  | 

protected by Community Sep 1 ’16 at 23:09

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count ).

Would you like to answer one of these unanswered questions instead?

Not the answer you’re looking for? Browse other questions tagged java android string file-io or ask your own question .

asked

5 years, 10 months ago

viewed

392,191 times

active

2 months ago

Linked

-1

How to create and write data a text file in android programatically?

-3

Save text/string internally Android

21

Write a string to a file

5

How to Cache Json data to be available offline?

4

ANDROID: How to save JSON data in a file and retrieve it?

2

How to write text to a file on external storage on android?

2

Save String as html file android

3

How to access /data folder of another application through your application?

1

saving JSON file from url in Internal Storage

0

Android: read large text file

see more linked questions…

Related

3428

How to read / convert an InputStream into a String in Java?

1292

How do I create a Java string from the contents of a file?

2694

How do I tell if a regular file does not exist in Bash?

3140

How do I make the first letter of a string uppercase in JavaScript?

3418

How to replace all occurrences of a string in JavaScript

3176

Why is the Android emulator so slow? How can we speed up the Android emulator?

7435

How to check whether a string contains a substring in JavaScript?

1204

How do I create a file and write to it in Java?

2667

How do I check if a string contains a specific word?

2668

How do I convert a String to an int in Java?

Hot Network Questions

  • Is the alliance responsible for tickets of bankrupt airline?

  • Would it be more efficient to build fleets in orbit?

  • What to do if you notice a substantial improvement to a result in a paper whilst refereeing it?

  • MOSFET W/L ratio limits: what’s (un)reasonable?

  • How do you get temporary hit points?

  • How to handle being asked to automate jobs as a temp worker

  • Combining first two letters from first name and first two letters from last name

  • What are these "pimples" on the jet engine for?

  • Ctrl + Alt + Del prior to Windows 10 logon no longer needed?

  • What is the utilitarian purpose of artificial waterfalls?

  • Is it possible to buy round-trip tickets to Jamaica where the return ticket is counterfeit?

  • Are these ‘French children held at gun point’?

  • Why do governments of developed countries care about mass protests?

  • Close all tabs in Safari except for one

  • What is a word for ascribing divine characteristics to a machine?

  • Would readers feel cheated if the villain is successful in convincing the protagonist to change sides?

  • Are there any gambits involving sacrificing a piece?

  • Why does 要 mean "will" and not "want" in this sentence?

  • What would be the necessary conditions to rain bubbles?

  • Was Japan known to be a potential threat to the USA in the 10 year period prior to 1941

  • What’s the best way to store over 400 GB of digital photos?

  • How do I get something sticky like honey or Golden Syrup off measuring spoons or measuring cups? Is there a better way?

  • Find the number of leading zeroes in a 64-bit integer

  • Homotheties: Let A and B be distinct points of a circle o. What is the set of possible centroids of triangles ABC with C ∈ o?

more hot questions


question feed

lang-java

Stack Overflow works best with JavaScript enabled