How to update a line in text file with id input - android

I have a text file is conten.txt which has
101,1,123
102,1,234
I am using Android to update that text file. With a input as "102", I want to update second line with information is "2,234". So it will be
102,2,234
Finally, the content in text file will be
101,1,123
102,2,234
Is it possible to do it in Android? This is my current work. However, tt only writes a new line in the file
String whole_content="102,2,234";
File file = new File(getApplicationContext().getFilesDir(), "conten.txt");
String filepath = Environment.getExternalStorageDirectory().getPath();
FileOutputStream outputStream;
try {
outputStream = openFileOutput("conten.txt", Context.MODE_PRIVATE);
outputStream.write(whole_content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

Yes it's possible! Simply, you could create a string of total file content and replace all the occurrence in the string and write that string to that file again.
File log= new File("yourFile");
String search = "102"; //Like you said
try{
FileReader fr = new FileReader(log);
String s;
String totalStr = "";
try (BufferedReader br = new BufferedReader(fr)) {
while ((s = br.readLine()) != null) {
if(s.contain(search)) {
s = search + "," + "yourReplaceString"; //You can extract it from your input
}
totolStr += s;
}
FileWriter fw = new FileWriter(log);
fw.write(totalStr);
fw.close();
}
}catch(Exception e){
e.printStackTrace();
}

Related

Extracting a storage_file's path then set it to a EditText and finally read that file using that path placed in EditText

Advance Thanks for your help!
I am searching for this solution for about two days but not solved yet. So, don't mark it as repetitive question.
Here, how I have tried-
Reading file path and setting to EditText: (it's working well)
I have used followings to read the file using that path-
buttond3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File folders = new File(Environment.getExternalStorageDirectory() + "/" + "Information Security"+"/"+"Decrypted Files");
if (!folders.exists()) {
folders.mkdirs();
}
try {
String path= String.valueOf(editTextd2.getText());
String plain = getStringFromFile(path);
String decrypted = Encryption_Decryption2.decrypt(plain, "000102030405060708090A0B0C0D0E0F");
String file_name= String.valueOf(editTextd4.getText());
File f = new File(folders + "/" + file_name);
FileOutputStream fileOutput = new FileOutputStream(f);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutput);
outputStreamWriter.write(decrypted);
outputStreamWriter.flush();
fileOutput.getFD().sync();
outputStreamWriter.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
Here is the getStringFromFile() method-
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
Just problem in reading the file using the path. Please help!!!

Read/Write ArrayList String to file

Hi I have same problem by Writing String ArrayList to file and Reading.
This is my code for writing
File SettingsPath = getFilesDir();
String strSettingsPath = SettingsPath.toString() + "/settings.txt";
File file = new File (strSettingsPath);
if (!file.exists()) {
File removeFile = new File(strSettingsPath.toString());
boolean deleted = removeFile.delete();
}
try {
FileOutputStream fos =
new FileOutputStream(
new File(strSettingsPath));
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this.strSettings);
os.close();
Log.v("","File has been written");
} catch(Exception ex) {
ex.printStackTrace();
}
And this is for Reading
public void reader(View v) throws FileNotFoundException {
File SettingsPath = getFilesDir();
String strSettingsPath = SettingsPath.toString() + "/settings.txt";
List<String> Settings = new ArrayList<String>();
BufferedReader readerL = new BufferedReader(new FileReader(strSettingsPath));
String line;
try{
//line = readerL.readLine();
while ((line = readerL.readLine()) != null) {
Settings.add(line);
System.out.println("The Setting line is " + Settings);
}
readerL.close();
}catch (IOException e){
e.printStackTrace();
}
By reading I get This
The Setting line is [����sr��java.util.ArrayListx����a���I��sizexp������w������t��]
The Setting line is [����sr��java.util.ArrayListx����a���I��sizexp������w������t��, test#test.comt��passwordt�� itdguccgjx]
and I need like this
test#test.com
password
itdguccgjx
What is wrong?
Sorry for my bad English.
Hi
I will like this.
Textbox1
Textbox2
Textbox3
.......
If I will get value of arraylist.get(1).tostring I get Textbox2

Save the text of a text field and then open a file on my device

I want to save the text the user puts in a text field and then compare it's strings with the names of the files located in a directory on my android device.
If it finds a file with the same name in that directory then it opens. (for now it would be a text file)
I would really appreciate to know, what should I do or how?
Like this?
public void getServerDetail() {
try {
File myFile = new File("/sdcard/RecordData.dat");
FileInputStream fstream = new FileInputStream(myFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] tokens = strLine.split(",");
dbName = tokens[0];
serverip = tokens[1];
serverport = tokens[2];
username = tokens[3];
password = tokens[4];
}
fstream.close();
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
Then use
if(Edittext.getText().toString().Equals(password)){}

How to overwrite a file in sdcard in android?

I need to read a file in the sd card in my android device and write the contents of this file into another file in the sd card which is already existing.
Here is my code to read a file anywhere in the sdcard.
public String readFromFile(String fileName) {
String ret = "";
try {
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard, fileName);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
if ( bufferedReader != null ) {
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
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;
}
Can some one please tell me how can I copy the contents of this file into another file on sdcard after reading.
I do not wish to append but to overwrite the contents of the file.
I need a method in this format
void writeFile(String fileName, String Data){
//code to overwite with given data
}
Can someone please help me
Thanks in advance.
void writeFile(String fileName, String data) {
File outFile = new File(Environment.getExternalStorageDirectory(), fileName);
FileOutputStream out = new FileOutputStream(outFile, false);
byte[] contents = data.getBytes();
out.write(contents);
out.flush();
out.close();
}
The most important part is the false in the FileOutputStream constructor. The second parameter is append. If set to false, the file will be overwritten if it exists.

Data missing when read from text file with line breaks in Android

I have three strings which write in to list.txt file with this code
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ;
FileOutputStream fop = null;
File file = null;
try {
file =new File(filename);
fop=new FileOutputStream(file,true);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
filecontent=filecontent+ System.getProperty ("line.separator");
// get the content in bytes
byte[] contentInBytes = filecontent.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (IOException e) {
e.printStackTrace();
}
The file output detail is
abc.mp3
cde.mp3
edf.mp3
Now, I want to read the detail in list.txt. I used below code but the output only has
cde.mp3
edf.mp3
What is happen with my code? I don't know why data abc.mp3 disappear.
ArrayList<String> data;
try {
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + FOLDER + "/" + "list.txt" ;
BufferedReader in = new BufferedReader(new FileReader(filename));
String audio_name;
audio_name = in.readLine();
data = new ArrayList<String>();
while ((audio_name = in.readLine()) != null) {
data.add(audio_name);
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
for (int i=0;i<data.size();i++)
{
Log.d("D",String.valueOf(data.get(i)));
}
The first instance of audio_name = in.readLine() would read the first line abc.mp3 but the input is not used. Thus first line read by your while loop and stored in data would be cde.mp3. You should remove the first instance of audio_name = in.readLine().
audio_name = in.readLine();
data = new ArrayList<String>();
You read your first line into your audio_name variable, but you never add it to the list, so that's why it's "missing".

Categories

Resources