How to remove specific line from the file - java

I am trying to delete a specific line from a file, but when I run this, it returns me all the files, deleted. More specific i have a favorite button at a video fragment and i want when user press it ,to write the title of video in file (already done) and when unpress it to delete it....
my.java class is:
private void writeToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/config.txt");
FileOutputStream fos = new FileOutputStream(file,true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (!file.exists()) {outputStreamWriter.write(g);}
outputStreamWriter.append("\n"+g +"\n");
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private void deleteToFile(String g,Context context) {
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
outputStreamWriter.write(text.toString());
}
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.favorite:
if(showingFirst==true) {
Context context = getActivity();
CharSequence text = "Added to Favorites";
int duration = Toast.LENGTH_SHORT;
item.setIcon(R.drawable.heart_off);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
writeToFile(title,context);
showingFirst=false;
} else {
Context context = getActivity();
CharSequence text = "Deleted from Favorites";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
deleteToFile(title,context);
item.setIcon(R.drawable.heart_wh);
showingFirst=true;
}
break;
case R.id.home:
Intent k=new Intent(getActivity(),MainActivity.class);
Log.i(TAG, "onNavigationItemSelected: ");
startActivity(k);
break;
}
return false;
}

So, problem lies at below line of codes where you are trying to open file for Read and Write simultaneously
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
Instead, I would suggest you to read your file completely and then at the end you should write to the file (overwrite).
try {
File file=new File("/data/data/com.holomedia.holomedia/files/config.txt");
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
if (!line.equals(g) && !g.equals("\n")){
text.append(line);
text.append('\n');
}
}
br.close();
//start writing from here
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
outputStreamWriter.write(text.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
}
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}

This line:
FileOutputStream fos = new FileOutputStream(file);
resets contents of the file (ie replaces it with empty file). I recommend you add logging and/or debug your code so you will have a better understanding of what is going on.

Related

AndroidStudio - save user info in CSV file and read it

I'm a newbie in programming on Android Studio. I'm trying to create a simple application to gain basic experience. In the application, I would need to store individual inputs to a file (ideally CSV) in internal memory. First of all, I am trying to save user data - my name and phone number. The save method looks like this:
public void save(View view)
{
String fileName = "user.csv";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(getFilesDir().getName(), ContextWrapper.MODE_PRIVATE);
File file = new File(directory, fileName);
String data = "FirstName,LastName,PhoneNumber";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
The data seems to be saved and I'm redirected to MainActivity. Here is the method:
protected void onCreate(Bundle savedInstanceState) {
File file = new File(getFilesDir(),"user.csv");
if(!file.exists()) {
Intent intent = new Intent(this, activity_login.class);
startActivity(intent);
}
else {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv_name = findViewById(R.id.tv_name);
TextView tv_phone = findViewById(R.id.tv_phone);
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("user.csv"));
while ((sCurrentLine = br.readLine()) != null) {
tv_name.setText(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
No value is stored in TextView tv_name and the box is empty. Where am I making mistake?
Thank you very much for your help!
For reading data saved use this method uses, UTF_8 ENCODING
public static String readAsString(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
String line;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
reader = new BufferedReader(new InputStreamReader(is,UTF_8));
}
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
return sb.toString();
}
Use this method as follows, parsing file "user.csv".
public static String readFileAsString(File file) throws IOException {
return readAsString(new FileInputStream(file));
}
Fetch string and set textView
Use as this to read file:
FileInputStream fis = new FileInputStream("your full file path");
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
Below is the code for creating .csv file and inserting data into it.
For more look into my answer :https://stackoverflow.com/a/48643905/8448886
CODE HERE:
String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv
//by Hiting button csv will create inside phone storage.
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CSVWriter writer = null;
try {
writer = new CSVWriter(new FileWriter(csv));
List<String[]> data = new ArrayList<String[]>();
data.add(new String[]{"Country", "Capital"});
data.add(new String[]{"India", "New Delhi"});
data.add(new String[]{"United States", "Washington D.C"});
data.add(new String[]{"Germany", "Berlin"});
writer.writeAll(data); // data is adding to csv
writer.close();
callRead();
} catch (IOException e) {
e.printStackTrace();
}
}
});

Read File From File Manager

I want to choose a file using the file chooser of android, then display its content in a EditText component.
I have this method where I open the file manager and search the file in Downloads
public void btnSearch(View view){
Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
fileIntent.setType("*/*");
fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(fileIntent,"Seleccione"),FILE_SELECTED_CODE);
} catch (android.content.ActivityNotFoundException ex){
System.out.println( ex.getMessage());
Toast.makeText(this,"Install a File Manager. ", Toast.LENGTH_SHORT).show();
}
}
And then I use this method to read the content of the file
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data == null)
return;
switch (requestCode){
case FILE_SELECTED_CODE:
if(resultCode == RESULT_OK){
Uri uri = data.getData();
String ruta = uri.getPath();
File archivo = new File(ruta);
try {
BufferedReader reader = new BufferedReader(new FileReader(archivo));
String linea = "";
String texto = "";
while((linea = reader.readLine()) != null){
texto += linea;
}
EditText tbxDatos = (EditText) findViewById(R.id.compDatos);
tbxDatos.setText(texto);
} catch(Exception e){
System.out.println( e.getMessage());
}
}
break;
}
super.onActivityResult(requestCode,resultCode,data);
}
But now I am having this exception when I select the file from the File Chooser:
Exception: /document/33 (No such file or directory)
Any ideas? Thank you.
Try this example Straight from the docs!!!
private String readTextFromUri(Uri uri) throws IOException {
InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
fileInputStream.close();
parcelFileDescriptor.close();
return stringBuilder.toString();
}

android.content.res.Resources$NotFoundException

hey I have a problem with loading data from a txt file
private void read() {
try {
// open the file for reading
InputStream instream = openFileInput(File.separator + "bla.txt");
// if file the available for reading
if (instream.available() >0) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine()) != null) {
for(int i= 0; i<=1; i++){
if(i == 0){
bla = Integer.parseInt(buffreader.readLine());
}
if(i == 1){
bla2 = Integer.parseInt(buffreader.readLine());
}
}
// close the file again
instream.close();
Toast.makeText(getBaseContext(),
"Ladevorgang war efolgreich!",
Toast.LENGTH_LONG).show();
}}
}
catch (java.io.FileNotFoundException e) {
Toast.makeText(getBaseContext(),
"Datei nicht vorhanden",
Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
Please help me I dont know what I should change:(
I alway got the android.content.res.Resources$NotFoundException: String resource ID #0x0
Thanks for help Strik3r
private void save() {
try {
File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
this is the save data
// open the file for reading
InputStream instream = openFileInput(File.separator + "bla.txt");
does not seem to be a valid file.
Instead, please try
InputStream instream = openFileInput(Environment.getExternalStorageDirectory() +File.separator + "bla.txt");

saving a text in the notepad in android

I just want to ask about my code whether it's right, because I can't load the text in my name.txt file.
Also I just want to know how to save the input text in my name.txt file.
load.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick
(View arg0) {
try{
StringBuffer sb=new StringBuffer();
FileInputStream fis=con.openFileInput("name.txt");
DataInputStream dis=new DataInputStream(fis);
String text=null;
while((text=dis.readLine())!=null)
sb.append(text+"\n");
dis.close();
et1.setText(sb.toString());
}catch
(IOException e){
Toast.makeText(con, "Could not find", Toast.LENGTH_LONG).show();
}
}
});
If you want to write data to file
static protected void writeToFile(String strToWrite)
{
try
{
BufferedWriter out = new BufferedWriter(new FileWriter("name.txt", true));
out.write(strToWrite);
out.close();
}
catch (IOException e) { e.printStackTrace();}
}
The code you have written is to read data from an existing file not to write in the file.
try
{
File file1 = new File(Environment.getExternalStorageDirectory() + "/dir/", "filename.extension");
FileWriter fw1 = new FileWriter(file1.getAbsoluteFile());
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write("Stringtowritetofile");
bw1.close();
}

Android Async task Run time Exception Error.

I am doing a decryption task in android platform. At first, I create a method called RunDecrypt. It's work fine when I press the button in my UI. The method shown below:
public void runDecrypt() throws IOException{
EditText editText = (EditText) findViewById(R.id.fileName);
EditText editText2 = (EditText) findViewById(R.id.keyName);
String fileName = editText.getText().toString();
String keyName = editText2.getText().toString();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard , fileName);
File key = new File(sdcard, keyName);
BufferedReader brFile;
String Cipher = null;
try{
//Read file line by line and concat each line of string in file with space character.
FileInputStream fstream = new FileInputStream(file);
brFile = new BufferedReader(new InputStreamReader(fstream));
String tempString;
while((tempString = brFile.readLine()) != null){
if(Cipher == null){
Cipher = tempString;
}else{
Cipher = Cipher.concat(" ");
Cipher = Cipher.concat(tempString);
}
}
}catch(Exception e){
//messageBox("Decrypt", e.getMessage());
}
BufferedReader brKey;
String DecKey = null;
try{
FileInputStream fstream = new FileInputStream(key);
brKey = new BufferedReader(new InputStreamReader(fstream));
DecKey = brKey.readLine();
}catch(Exception e){
//messageBox("Decrypt", e.getMessage());
}
try{
byte[] cipherByte = DES.parseBytes(Cipher);
String decKey = DES.convertStringToHex(DecKey);
byte[] keyByte = DES.parseBytes(decKey);
String decryptResult = DES.hex(DES.decryptCBC(cipherByte, keyByte));
String temp = decryptResult.replace(" ", "");
String finalDecrypt = temp.substring(0, (temp.length() - DES.getConcatCount()));
String finResult = DES.convertHexToString(finalDecrypt);
TextView FinalResult = (TextView)findViewById(R.id.decryptText);
FinalResult.setText(finResult);
}catch(Exception e){
messageBox("Decrypt", "Please Upload File Properly");
}
}
Since it's work fine, I try to implement this method with Async Task for running my work in background. The class that implemented shown below:
private class runDecrypt extends AsyncTask <URL , Integer, Long> {
private final ProgressDialog dialog = new ProgressDialog(Homepage.this);
AlertDialog.Builder builder = new AlertDialog.Builder(Homepage.this);
#SuppressWarnings("resource")
#Override
protected Long doInBackground(URL... params) {
EditText editText = (EditText) findViewById(R.id.fileName);
EditText editText2 = (EditText) findViewById(R.id.keyName);
String fileName = editText.getText().toString();
String keyName = editText2.getText().toString();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard , fileName);
File key = new File(sdcard, keyName);
BufferedReader brFile;
String Cipher = null;
try{
//Read file line by line and concat each line of string in file with space character.
FileInputStream fstream = new FileInputStream(file);
brFile = new BufferedReader(new InputStreamReader(fstream));
String tempString;
try {
while((tempString = brFile.readLine()) != null){
if(Cipher == null){
Cipher = tempString;
}else{
Cipher = Cipher.concat(" ");
Cipher = Cipher.concat(tempString);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(java.io.FileNotFoundException e){
System.out.println("File could not be found.");
}
BufferedReader brKey;
String DecKey = null;
try{
FileInputStream fstream = new FileInputStream(key);
brKey = new BufferedReader(new InputStreamReader(fstream));
try {
DecKey = brKey.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(java.io.FileNotFoundException e){
System.out.println("Key file could not be found.");
}
String decKey = DES.convertStringToHex(DecKey);
byte[] cipherByte = DES.parseBytes(Cipher);
byte[] keyByte = DES.parseBytes(decKey);
String decryptResult = DES.hex(DES.decryptCBC(cipherByte, keyByte));
String temp = decryptResult.replace(" ", "");
String finalDecrypt = temp.substring(0, (temp.length() - DES.getConcatCount()));
String finResult = DES.convertHexToString(finalDecrypt);
TextView FinalResult = (TextView)findViewById(R.id.decryptText);
FinalResult.setText(finResult);
return null;
}
protected void onPreExecute() {
this.dialog.setMessage("Decrypting...");
this.dialog.show();
}
protected void onPostExecute(Long result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
builder.setMessage("Decryption Completed");
builder.show();
}
protected void onProgressUpdate(int progress) {
setProgress(progress * 100);
}
}
My onClick method:
public void onClick (View v){
Intent browse = new Intent(this, Browse.class);
switch (v.getId()){
case R.id.browseFile:
browse.putExtra("browse","file");
startActivityForResult(browse, 1);
break;
case R.id.browseKey:
browse.putExtra("browse", "key");
startActivityForResult(browse, 1);
break;
case R.id.decrypt:
new runDecrypt().execute();
break;
default:
break;
}
}
My logcat shown below:
Can Anyone please help? Thank you and appreciated!
There are various issues with your code, but the cause of the particular exception is explained right there in Logcat:
Only the original thread that created a view hierarchy can touch its views.
The line in question is com.example.descracker.Homepage:245 where you invoke setText() on a TextView from an AsyncTask. You will have to move this logic into the UI thread, for instance through AsyncTask's facility functions onPreExecute(), onPostExecute() or onProgressUpdate(), or by posting a delayed action to the view itself using post(Runnable).
Also, please follow Java coding conventions and start your variables names with a lowercase letter.
As Shashank kadhe mentioned try this in your onPostExecute method and please change it according to your own need.
protected void onPostExecute(String file_url) {
String fileName = editText.getText().toString();
String keyName = editText2.getText().toString();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard , fileName);
File key = new File(sdcard, keyName);
BufferedReader brFile;
String Cipher = null;
try{
//Read file line by line and concat each line of string in file with space character.
FileInputStream fstream = new FileInputStream(file);
brFile = new BufferedReader(new InputStreamReader(fstream));
String tempString;
while((tempString = brFile.readLine()) != null){
if(Cipher == null){
Cipher = tempString;
}else{
Cipher = Cipher.concat(" ");
Cipher = Cipher.concat(tempString);
}
}
}catch(Exception e){
//messageBox("Decrypt", e.getMessage());
}
BufferedReader brKey;
String DecKey = null;
try{
FileInputStream fstream = new FileInputStream(key);
brKey = new BufferedReader(new InputStreamReader(fstream));
DecKey = brKey.readLine();
}catch(Exception e){
//messageBox("Decrypt", e.getMessage());
}
try{
byte[] cipherByte = DES.parseBytes(Cipher);
String decKey = DES.convertStringToHex(DecKey);
byte[] keyByte = DES.parseBytes(decKey);
String decryptResult = DES.hex(DES.decryptCBC(cipherByte, keyByte));
String temp = decryptResult.replace(" ", "");
String finalDecrypt = temp.substring(0, (temp.length() - DES.getConcatCount()));
String finResult = DES.convertHexToString(finalDecrypt);
TextView FinalResult = (TextView)findViewById(R.id.decryptText);
FinalResult.setText(finResult);
}catch(Exception e){
messageBox("Decrypt", "Please Upload File Properly");
}
}
Since it's work fine, I try to implement this method with Async Task for running my work in background. The class that implemented shown below:
private class runDecrypt extends AsyncTask <URL , Integer, Long> {
private final ProgressDialog dialog = new ProgressDialog(Homepage.this);
AlertDialog.Builder builder = new AlertDialog.Builder(Homepage.this);
#SuppressWarnings("resource")
#Override
protected Long doInBackground(URL... params) {
EditText editText = (EditText) findViewById(R.id.fileName);
EditText editText2 = (EditText) findViewById(R.id.keyName);
String fileName = editText.getText().toString();
String keyName = editText2.getText().toString();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard , fileName);
File key = new File(sdcard, keyName);
BufferedReader brFile;
String Cipher = null;
try{
//Read file line by line and concat each line of string in file with space character.
FileInputStream fstream = new FileInputStream(file);
brFile = new BufferedReader(new InputStreamReader(fstream));
String tempString;
try {
while((tempString = brFile.readLine()) != null){
if(Cipher == null){
Cipher = tempString;
}else{
Cipher = Cipher.concat(" ");
Cipher = Cipher.concat(tempString);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(java.io.FileNotFoundException e){
System.out.println("File could not be found.");
}
BufferedReader brKey;
String DecKey = null;
try{
FileInputStream fstream = new FileInputStream(key);
brKey = new BufferedReader(new InputStreamReader(fstream));
try {
DecKey = brKey.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}catch(java.io.FileNotFoundException e){
System.out.println("Key file could not be found.");
}
String decKey = DES.convertStringToHex(DecKey);
byte[] cipherByte = DES.parseBytes(Cipher);
byte[] keyByte = DES.parseBytes(decKey);
String decryptResult = DES.hex(DES.decryptCBC(cipherByte, keyByte));
String temp = decryptResult.replace(" ", "");
String finalDecrypt = temp.substring(0, (temp.length() - DES.getConcatCount()));
String finResult = DES.convertHexToString(finalDecrypt);
TextView FinalResult = (TextView)findViewById(R.id.decryptText);
FinalResult.setText(finResult);
}
}

Categories

Resources