How to save durably a file on internal storage - android

I am currently encountering a problem saving a text file on the internal storage.
The problem is that whenever i exit the application, the file seems to be deleted.
I wrote this method that is called at the start of the application, to create a blank text file :
private void init() {
String FILE_NAME = "save.txt";
try {
new BufferedWriter(new FileWriter(getFilesDir() + FILE_NAME));
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
this function is called to read all lines written in it :
private List<String> readFromFile() {
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = new FileInputStream(getFilesDir()+"save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
return ret;
}
And finaly this method is called to append a string in the text file if it's not already in it :
private void save(String unNom) {
String FILE_NAME = "save.txt";
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = new FileInputStream(getFilesDir()+"save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
if(!ret.contains(unNom)){
ret.add(unNom);
}
bReader.close();
FileOutputStream fos = new FileOutputStream(getFilesDir() +FILE_NAME);
for (String ligne: ret) {
ligne+="\n";
fos.write(ligne.toString().getBytes());
}
fos.flush();
fos.close();
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
What should I do to save correctly the file in the internal storage ?
Sorry for my bad english,
Thank you for your help !

The init was'nt necessary. I removed the method and I edited the save method, so it could create a new file if a not found exception was raised :
private void save(String unNom) {
String FILE_NAME = "save.txt";
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = openFileInput("save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
if (!ret.contains(unNom)) {
ret.add(unNom);
}
bReader.close();
FileOutputStream fos = null;
fos = openFileOutput("save.txt", this.MODE_PRIVATE);
for (String ligne : ret) {
ligne = "\n" + ligne;
fos.write(ligne.getBytes());
}
fos.close();
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
try {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
FileOutputStream fos = null;
fos = openFileOutput("save.txt", this.MODE_PRIVATE);
fos.write(unNom.getBytes());
fos.close();
Toast.makeText(this, "NEW FILE", Toast.LENGTH_LONG).show();
}
catch(Exception e2){}
}
}

Related

How to read a .txt file with multiple lines?

I want to save my data in a .txt file. In another activity I want to be able to read the saved data. I want to save multible values each time and put them together on a line, the next values need to be in a new line. I tried \n System.getProperty("line.separator"); System.lineSeparator(); and \n\r to start in a new line but this doesn't seem to work while the data still end up behind each other instead of being on another line.
I use this code to write to the file:
Context context = getApplicationContext();
writedatatofile(context);
protected void writedatatofile(Context context){
try
{
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("data_log.txt", Context.MODE_APPEND));
String data;
if (newstart){
data = "Exersice started \n" + "t.s a.s t.a a.a cnst";
} else {
data = (Integer.toString(time_step)+Integer.toString(new_average_step)+Integer.toString(time_footaid)+Integer.toString(new_average_aid)+Boolean.toString(rhythmconsistent)+"\n");
}
outputStreamWriter.append(data);
outputStreamWriter.close();
Toast.makeText(this, "Data has been written to File", Toast.LENGTH_SHORT).show();
}
catch(IOException e) {
e.printStackTrace();
}
}
and this code to read the file:
Context context = getApplicationContext();
String fileData = readFromFile(context, fileName);
TextView datalog = findViewById(R.id.datalog);
datalog.setText(fileData);
private String readFromFile(Context context, String fileName){
String ret = " ";
try {
InputStream inputStream = context.openFileInput(fileName);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
Toast.makeText(this, "Data received", Toast.LENGTH_SHORT).show();
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
} else {
Toast.makeText(this, "No data received", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e){
Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
} catch (IOException e){
Toast.makeText(this, "Can not read file", Toast.LENGTH_SHORT).show();
}
return ret;
}
As mentioned "\n" doesn't solve the problem but is also doesn't show up in my dataas \n. So it is not stored as a normal String.
When you write the file:
BufferedWriter writer = new BufferedWriter(outputStreamWriter);
writer.write(data);
writer.newLine(); // <-- this is the magic
writer.close();
You can read the data from .txt file using below code.
File exportDir = new File(Environment.getExternalStorageDirectory(), File.separator + "bluetooth/abc.txt");
if (exportDir.exists()) {
FileReader file = null;
try {
file = new FileReader(exportDir);
BufferedReader buffer = new BufferedReader(file);
String line = "";
int iteration = 0;
while ((line = buffer.readLine()) != null) { //read next line
if (iteration == 0) { //Skip the 1st position(header)
iteration++;
continue;
}
StringBuilder sb = new StringBuilder();
String[] str = line.split(",");
//get the single data from column
String text1 = str[1].replace("\"", "");
String text2 = str[2].replace("\"", "");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

android replace string by another string in file on sdcard

I've created Test.txt on sdcard and write string "test example" on it.
after that, I replace string "test" by "etc" in Test.txt.
this is my code :
String origin_str, old_str , new_str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t2);
origin_str = "test example";
old_str = "test";
new_str = "etc";
Button bt_create2 = (Button)findViewById(R.id.bt_createfileT2);
bt_create2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
File file = new File(newFolder, "Test" + ".txt");
if (!file.exists()) {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(origin_str);
myOutWriter.close();
fOut.close();
}
} catch (Exception e) {
System.out.println("e: " + e);
}
}
});
Button bt_replacefileT2 = (Button)findViewById(R.id.bt_replacefileT2);
bt_replacefileT2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
FileInputStream in = new FileInputStream(file);
int len = 0;
byte[] data1 = new byte[1024];
while ( -1 != (len = in.read(data1)) ){
if(new String(data1, 0, len).contains(old_str)){
String s = "";
s = s.replace(old_str, new_str);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
with this code, it was create Test.txt on sdcard and write "test example" on it.
but when replace string "test" by "etc", it not working.
how to fix it?
I will give my code, always worked for me :)
Hope thi can help you :DD
public void saveString(String text){
if(this.isExternalStorageAvailable()){
if(!this.isExternalStorageReadOnly()){
try {
FileOutputStream fos = new FileOutputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeBytes(text);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
//Toast.makeText(main, "Eror saving String", Toast.LENGTH_SHORT).show();
}
}
}
}
private static boolean isExternalStorageAvailable(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(estadoSD))
return true;
return false;
}
private static boolean isExternalStorageReadOnly(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(estadoSD))
return true;
return false;
}
public String getString(){
FileInputStream fis = null;
ObjectInputStream ois = null;
if(this.isExternalStorageAvailable()) {
try {
fis = new FileInputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ois = new ObjectInputStream(fis);
String text = (String)ois.readObject();
return familia;
} catch (FileNotFoundException e) {
//Toast.makeText(main, "The file text doesnt exist", Toast.LENGTH_SHORT).show();
} catch (StreamCorruptedException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch(EOFException e){
try {
if(ois != null)
ois.close();
if(fis != null)
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
//Toast.makeText(main, "eror reading file", Toast.LENGTH_SHORT).show();
} catch (ClassNotFoundException e) {
//Toast.makeText(main, "String class doesnt exist", Toast.LENGTH_SHORT).show();
}
}
return null;
}
try this
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
line = line.replace(old,new);
}
br.close();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.write(line);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}

Android Studio Saving Data to Phone

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

Saving int values to SD and read them

I have succesfully saved int values to sd but cant read. It always gives numberformat information. I made all logics, but cant find why it gives error.
Here is my code ;
this my constant
private final static String EXTERNAL_FILES_DIR = "ARDROID";
private final static String FILE_NAME = "turkcell.txt";
private boolean isThereAnySavedFile = false;
when this method called, it tries to open file, if file does not exist, create the file
public void anySavedDataInSD() {
String textFromSD = String.valueOf(read());
if (isThereAnySavedFile) {
int numberOfSendedSMS = Integer.parseInt(textFromSD.toString());
numberOfSendedSMS++;
writeToSD(String.valueOf(numberOfSendedSMS));
} else {
int first=60;
String g = String.valueOf(first);
writeToSD(g);
}
}
this method for writing
private void write(File file, String msg) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(msg.getBytes());
Logger.info("oldu bu kez");
} catch (IOException e) {
Logger.info("oldu bu kez2" + e);
} finally {
Logger.info("oldu bu kez3");
try {
if (outputStream != null)
outputStream.close();
} catch (IOException exception) {
}
}
}
this methof for reading
public StringBuilder read() {
StringBuilder textBuilder = new StringBuilder();
BufferedReader reader = null;
try {
File externalFilesDir = getExternalFilesDir(EXTERNAL_FILES_DIR);
File file = new File(externalFilesDir, FILE_NAME);
Logger.info("oldu2");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
isThereAnySavedFile = true;
} catch (FileNotFoundException e) {
Logger.info("oldu3");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return textBuilder;
}

Why reading text from sd card files returns null in android?

I want to retain some strings even when i clear my app data so i am using text files saved in sd card.
I am using sd card files to store myStrings and read them at run time. but each and every time readfile return null.
following is my code:
protected void writeToFile(String data, String fileName) {
String root_sd = Environment.getExternalStorageDirectory().toString();
File dir = new File(root_sd+"/"+"AntiVirusPref");
if(dir.mkdir())
{
File f=new File( dir.getAbsolutePath()+"/"+fileName);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else {
File f=new File( dir.getAbsolutePath()+"/"+fileName);
if (f.exists()) {
f.delete();
}
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(fileName, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
protected String readFromFile(String fileName, String defaultValue) {
String ret = "";
String root_sd = Environment.getExternalStorageDirectory().toString();
File dir = new File(root_sd+"/"+"AntiVirusPref");
File file = new File(dir.getAbsolutePath() + "/"+fileName);
try {
//InputStream inputStream = openFileInput("/sdcard/"+fileName);
FileInputStream inputStream = new FileInputStream(file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
/*if((receiveString = bufferedReader.read) != null){
stringBuilder.append(receiveString);
}*/
String line="";
int c;
while ((c = bufferedReader.read()) != -1) {
line+=(char)c;
//counter++;
}
stringBuilder.append(line);
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());
}
if (ret.equals("")) {
ret=defaultValue;
}
return ret;
}
try to add the "file:///" suffix before the Uri

Categories

Resources