Você está na página 1de 5

java - How To Read/Write String From A File In Android - Stack Overflow

1 of 5

http://stackoverflow.com/questions/14376807/how-to-read-write-string-...

sign up

log in

tour

help

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no
registration required.

careers 2.0

How To Read/Write String From A File In Android

I searched and went through most of the questions here, none of which seemed to solve my situation.
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
import
import
import
import
import
import
import
import
import
import
import

android.app.Activity;
android.content.Context;
android.content.Intent;
android.net.Uri;
android.os.Bundle;
android.telephony.TelephonyManager;
android.view.Menu;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.EditText;
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
save.setOnClickListener(new OnClickListener() {
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

edited Jan 17 '13 at 10:43


Jean-Franois Corbett
17.6k 9 49 82

asked Jan 17 '13 at 10:20


Major Aly
114 1 1 12

the question is "how to read/write to/from file?" Good.Dima 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

9/19/2014 6:57 AM

java - How To Read/Write String From A File In Android - Stack Overflow

2 of 5

http://stackoverflow.com/questions/14376807/how-to-read-write-string-...

2 BTW, be sure you put permission to the mainfest file, to operate with storage... Good.Dima 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

4 Answers
Hope this might be useful to you.
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt"
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.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) {
answered Jan 17 '13 at 10:39
R9J
1,268 1 5 14
Thank You, your method worked along with something I conjured. Major Aly Jan 18 '13 at 0:40
You are welcome:) R9J Jan 18 '13 at 4:11

9 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

1 @R9j Thankyou.. :) :) it worked perfectly Adarsh Gumashta Jan 5 at 13:22


1 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 at
23:57

9/19/2014 6:57 AM

java - How To Read/Write String From A File In Android - Stack Overflow

3 of 5

http://stackoverflow.com/questions/14376807/how-to-read-write-string-...

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();
}
answered Jul 23 '13 at 15:08
Eugene
9,218 32 101 199

1 App !? what does it supposed to be !? Laszlo-Andras Zsurzsa Jun 8 at 19:26

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:
String path = context.getFilesDir().getAbsolutePath();
For the external storage (SD card), use:
String path = context.getExternalFilesDir(null).getAbsolutePath();
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
Files.write("text-to-write", file, "UTF-8");
Read the file to a string
int length = (int) file.length();
byte[] bytes = new byte[length];

9/19/2014 6:57 AM

java - How To Read/Write String From A File In Android - Stack Overflow

4 of 5

http://stackoverflow.com/questions/14376807/how-to-read-write-string-...

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.
edited Feb 28 at 12:31

answered Feb 28 at 10:48


SharkAlley
2,309 17 22

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 at 5:55

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.

9/19/2014 6:57 AM

java - How To Read/Write String From A File In Android - Stack Overflow

5 of 5

http://stackoverflow.com/questions/14376807/how-to-read-write-string-...

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.
answered Jan 17 '13 at 10:28
Raj
1,010 11 29

Not the answer you're looking for? Browse other questions tagged java

android

string file-io or ask your own question.

9/19/2014 6:57 AM

Você também pode gostar