I want to read a text file that i had write in another activity using OutputStreamWriter.
this is my readFromFile method in Sale.java:
private int readFromFile(String request) {
int res = 0;
try {
//InputStream inputStream = openFileInput("dalassnums.txt");
File file=new File("dalassnums.txt");
InputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null ) {
String s=bufferedReader.readLine();
if(receiveString==request) {
res=Integer.valueOf(s);
break;
}
}
inputStream.close();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
res=0;
} catch (IOException e) {
//Log.e("login activity", "Can not read file: " + e.toString());
}
return res;
}
And this is writeToFile method in MainActivity.java:
private void writeToFile2(String numchar) {
try {
//File file=new File("dalassnums.txt");
//OutputStream outputStream=new FileOutputStream(file);
OutputStreamWriter outputStreamWriter;
if(numchar=="1") outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_PRIVATE));
else outputStreamWriter = new OutputStreamWriter(openFileOutput("dalassnums.txt", Context.MODE_APPEND));
for(int k=0; k<imageNums.size();k+=2){
outputStreamWriter.append(imageNums.get(k));
outputStreamWriter.append("\n");
outputStreamWriter.append(imageNums.get(k+1));
outputStreamWriter.append("\n");
}
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
When performing readFromFile, it returns 0 that means file not found;
I read about passing context but i don't know what context to pass; And wondering if there is any other way than passing context.
Any help would be appreciated.
Use : openFileInput in readFromFile, look here for example:
openFileInput() and/or openFileOutput() i/o streams silently failing
Another problem is that this is invalid:
if(numchar=="1")
you should
if(numchar.equals("1"))
otherwise you compare reference values instead content of string
Related
I have an app that saves Strings to textfile when closing the app and reads them in again on starting the app. If i destroy my app 1 time the data reappears and if i destroy it a 2nd time it reappears again. However when i destroy it the 3rd time all the data is lost.
I've tried everything but it just dont work, i've tried using onsavedinstancestate() etc but im lost.. If anyone could point me in the right direction i would really appreciate it!
My readFromFile() and writeToFile() methods:
private void writeToFile(String data, Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("start.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("start.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());
}
I'm working on Aosp. I want to keep a variable in the system but When I use a shared preference, the variable is deleted when I perform a Factory reset. I need to change and save the variable I want to keep. Think like a Mac address
You can put all the variables you want to save into a json and save it in internal storage
and you can retrive it whenever you want
example code for read and write
private void saveConfig(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
} }
private String readConfig() {
String data = "";
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();
data = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("Error", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("Error", "Can not read file: " + e.toString());
}
return data;
}
and your json can be
{
"variable1": "Value",
"variable2": false
}
i wanted to write and read data into/from a file.
I have searched and founnd these two methods which work perfectly..
public 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());
}
}
public 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;
}
But this file is being deleted when i remove the application from my android device.
Is there any method to save and retrieve data whatever if the user deleted the app ?
You can't. When removing an app, the files in it's local storage are removed.
You can however save your files in an external directory. That way, they aren't deleted when the user removes the app. You can read more about it here.
String myString = "hello world";
How could I save the contents of myString into a .txt file within the Phone/Android, which will be there after the application ends and so that I can edit the value in future?
Use this method:
public void WriteToFile(String str)
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());
}
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) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
I have an utility class named 'MyClass'. The class has two methods to read/write some data into phone's internal memory. I am new to android, Please follow below code.
public class MyClass {
public void ConfWrite() {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
while executing ConfWrite method, it fails
please provide a better solution to solve this
thanks in advance
You can Read/ Write your File in data/data/package_name/files Folder by,
To Write
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
To Read
BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(getFilesDir()+File.separator+"MyFile.txt")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = bufferedReader.readLine()) != null){
builder.append(read);
}
Log.d("Output", builder.toString());
bufferedReader.close();
public static void WriteFile(String strWrite) {
String strFileName = "Agilanbu.txt"; // file name
File myFile = new File("sdcard/Agilanbu"); // file path
if (!myFile.exists()) { // directory is exist or not
myFile.mkdirs(); // if not create new
Log.e("DataStoreSD 0 ", myFile.toString());
} else {
myFile = new File("sdcard/Agilanbu");
Log.e("DataStoreSD 1 ", myFile.toString());
}
try {
File Notefile = new File(myFile, strFileName);
FileWriter writer = new FileWriter(Notefile); // set file path & name to write
writer.append("\n" + strWrite + "\n"); // write string
writer.flush();
writer.close();
Log.e("DataStoreSD 2 ", myFile.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readfile(File myFile, String strFileName) {
String line = null;
try {
FileInputStream fileInputStream = new FileInputStream(new File(myFile + "/" + strFileName)); // set file path & name to read
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // create input steam reader
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) { // read line by line
stringBuilder.append(line + System.getProperty("line.separator")); // append the readed text line by line
}
fileInputStream.close();
line = stringBuilder.toString(); // finially the whole date into an single string
bufferedReader.close();
Log.e("DataStoreSD 3.1 ", line);
} catch (FileNotFoundException ex) {
Log.e("DataStoreSD 3.2 ", ex.getMessage());
} catch (IOException ex) {
Log.e("DataStoreSD 3.3 ", ex.getMessage());
}
return line;
}
use this code to write --- WriteFile(json); // json is a string type
use this code to read --- File myFile = new File("sdcard/Agilanbu");
String strObj = readfile(myFile, "Agilanbu.txt");
// you can put it in seperate class and just call it where ever you need.(for that only its in static)
// happie coding :)