I have a .txt file which contains let's say
1;2;3;4;5
a;b;c;d;e
A;B;C;D;E
And I would like to remove the line which begins with "a"
I made a copy of the file and write there the lines unless the line equals the lineToRemove
So here what's I did but the file hasn't change
String path = "playlist.txt"
String lineToRemove = "a";
public boolean removeLineFromFile(String lineToRemove) {
try {
File inFile = new File(path);
//Creating a temp file
File tempFile = new File(inFile.getAbsolutePath()+".tmp");
FileInputStream fIn = openFileInput(path);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fOut_temp = openFileOutput(path +".tmp", Context.MODE_APPEND);
OutputStreamWriter osw_temp = new OutputStreamWriter(fOut_temp);
osw_temp.write("");
String line = br.readLine();
//Read from the original file and write to the new
//unless content matches data to be removed.
while (line != null) {
String[] tokens = line.split(";");
if (! tokens[0].equals(lineToRemove)){
osw_temp.write(line);
osw_temp.flush();
}
line = br.readLine();
}
osw_temp.close();
br.close();
//Delete the original file
inFile.delete();
//Rename the new file to the filename the original file had.
tempFile.renameTo(inFile);
return true;
}catch (Exception ex) { return false;}
I think there is a problem with using File, is there another way of writing on android internal storage ?
Thanks in advance for your help
EDIT : because using File = new File + rename + deleted methods weren't working here is the solution that I find out. Maybe not the best but at least it works
try {
FileInputStream fIn = openFileInput(path);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
//Create temp file
FileOutputStream fOut2 = openFileOutput("te.txt", Context.MODE_WORLD_WRITEABLE);
OutputStreamWriter osw2 = new OutputStreamWriter(fOut2);
osw2.write("");
// save and close
osw2.flush();
osw2.close();
// Adding things to temp file
FileOutputStream fOut_temp = openFileOutput("te.txt", Context.MODE_APPEND);
OutputStreamWriter osw_temp = new OutputStreamWriter(fOut_temp);
osw_temp.write("");
String line = br.readLine();
//Read from the original file and write to the new
//unless content matches data to be removed.
while (line != null) {
String[] tokens = line.split(";");
if (! tokens[0].equals(lineToRemove)){
osw_temp.write(line);
osw_temp.write("\r\n");
osw_temp.flush();
}
line = br.readLine();
}
osw_temp.close();
br.close();
//Delete the original file
FileOutputStream fOut = openFileOutput(path, Context.MODE_WORLD_WRITEABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("");
// save and close
osw.flush();
osw.close();
//Copy temp file to original file
FileInputStream fIn3 = openFileInput("te.txt");
InputStreamReader isr3 = new InputStreamReader(fIn3);
BufferedReader br2 = new BufferedReader(isr3);
String line4 = br2.readLine() ;
FileOutputStream fOut_temp4 = openFileOutput(path, Context.MODE_APPEND);
OutputStreamWriter osw_temp4 = new OutputStreamWriter(fOut_temp4);
while (line4 != null) {
osw_temp4.write(line4);
osw_temp4.write("\r\n");
osw_temp4.flush();
Toast.makeText(getApplicationContext(),"ecrit", Toast.LENGTH_SHORT).show();
line4 = br2.readLine();
}
osw_temp4.close();
br2.close();
return true;
}catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.getMessage(), Toast.LENGTH_SHORT).show();
return false;}
}
Using this with Java I'm able to remove the line starts with a, just port in Android thats it.
public class LineRemover
{
static String path = "temp.txt";
static String lineToRemove = "a";
public static void main(String[] args)
{
try {
File inFile = new File(path);
FileInputStream fIn = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fOut_temp = new FileOutputStream("te.txt");
OutputStreamWriter osw_temp = new OutputStreamWriter(fOut_temp);
osw_temp.write("");
String line = br.readLine();
//Read from the original file and write to the new
//unless content matches data to be removed.
while (line != null) {
String[] tokens = line.split(";");
if (! tokens[0].equals(lineToRemove)){
osw_temp.write(line);
osw_temp.flush();
}
line = br.readLine();
}
osw_temp.close();
br.close();
inFile.delete();
inFile = new File("te.txt");
//Rename the new file to the filename the original file had.
inFile.renameTo(new File("temp.txt"));
}catch (Exception ex)
{}
}
}
Related
I create and manage file from android application with this code but what I want then its to delete it.
This is the code how I write and read it:
private String readDataFromString()
{
try{
FileInputStream fis = this.openFileInput("encryptedNotePad.txt");
InputStreamReader isr = new InputStreamReader(fis);
char[] inputBuffer = new char[100];
String s = "";
int charRead;
while((charRead = isr.read(inputBuffer)) > 0){
// Convertimos los char a String
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[100];
}
isr.close();
return s;
}catch (IOException ex){
ex.printStackTrace();
}
return null;
}
private void writeDataToString (String data) throws FileNotFoundException {
try{
//FileOutputStream fos = openFileOutput("encryptedNotePad.txt", MODE_PRIVATE);
FileOutputStream fos = this.openFileOutput("encryptedNotePad.txt", MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
// Escribimos el String en el archivo
osw.write(data);
osw.flush();
osw.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
How Can I delete it?
I found this:
File file = new File(selectedFilePath);
boolean deleted = file.delete();
But, I dont know the file path.Whats the file path?
But, I dont know the file path.Whats the file path?
Path means the file's path where you can get access to it or doing stuff on it.
I believe in your case, it will be:
encryptedNotePad.txt
Like you used it already:
FileOutputStream fos = this.openFileOutput("encryptedNotePad.txt", MODE_PRIVATE);
So if you give the path to the following code, it should work fine I hope:
File file = new File("encryptedNotePad.txt");
boolean deleted = file.delete();
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!!!
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
I'm trying to access the file path of my assets folder but for some reason, I can't access it and it creates an error(Unable to start activity ComponentInfo, Host name may not be null). What should be the correct syntax for this?
This is my code:
String xml = parser.getXmlFromUrl("file:///android_assets/music.xml");
and this is my file location:
Am I doing it properly? Or is my syntax incorrect?
try this, open an input stream on that file.
InputStreamReader is= new InputStreamReader(
context.getAssets().open("abc.xml"));
and then open and then
int length = is.available();
byte[] data = new byte[length];
is.read(data);
String xmlString = new String(data);
Hope It will help
Maybe
AssetManager assetManager = getAssets();
InputStream input = assetManager.open(fileName);
And after read file?
try using by filedescriptor as
AssetFileDescriptor descriptor = getAssets().openFd("myfile.txt");
FileReader reader = new FileReader(descriptor.getFileDescriptor());
Please use this code, its working code for text file as well as xml file.
public String readFromAssetsFolder(String fileName) {
String readValue = "";
InputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader input = null;
try {
fileInputStream = getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
inputStreamReader = new InputStreamReader(fileInputStream);
input = new BufferedReader(inputStreamReader);
String line = "";
while ((line = input.readLine()) != null) {
readValue = readValue+ line;
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (inputStreamReader != null)
inputStreamReader.close();
if (fileInputStream != null)
fileInputStream.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return readValue;
}
I'm tired messing around.
And i'm beginning to believe that it actually isn't possible.
Where do i find a simple example showing how to write a file "myPath/myFile.txt"?
And then reading it back again?
This an example of a code block that i can't get to work:
if(pathExists(path, ctx))
{
File file = new File(ctx.getFilesDir().getAbsolutePath() +"/" + path, fileName);
FileInputStream fIn = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fIn);
StringWriter writer = new StringWriter();
IOUtils.copy(fIn, writer, "UTF-8");
fileStr = writer.toString();
}
This is the error that i get:
"java.io.IOException: Is a directory"
This following snippet will copy you files which are saved in the application space to your desired path.
File mfile=new File("/data/data/src.com.file.example/files");
File[] list=mfile.listFiles();
// The path where you like to save your files
String extStorageDirectory = "/mnt/sdcard/backup/";
File file23 = null;
File fr = null;
for(int i =0;i<list.length;i++){
File myNewFolder = new File(extStorageDirectory +list[i].getName().substring(0,5));
if(myNewFolder.exists()){
String selectedFilePathq = "data/data/src.com.file.example/file/"+list[i].getName();
file23 = new File(selectedFilePathq);
fr = new File(myNewFolder+"/"+list[i].getName());
}else{
myNewFolder.mkdir();
String selectedFilePathq = "data/data/src.com.file.example/files /"+list[i].getName();
file23 = new File(selectedFilePathq);
fr = new File(myNewFolder+"/"+list[i].getName());
}
try {
copy(file23,fr);
} catch (IOException e) {
e.printStackTrace();
}
}
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
You could not write to Android internal storage (not unless your device is rooted) aside from the private file space assigned to your own application by the android system.
String strfile1 = getApplicationContext().getFilesDir().getAbsolutePath() + "/serstatus.txt" ;
File f1 = new File(strfile1);
you have to use serialization methods as in java.
to save an text as file you should be using FileOutputStream and to read the file you should be using FileInputStream. You can check the following code it has a simple edittext and two buttons one to save and one to read data saved in that file.
The following code is to save text in the file named raksi.
Button savebutton = (Button)findViewById(R.id.but);
savebutton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
e= (EditText)findViewById(R.id.edit);
StringBuffer sb = new StringBuffer();
sb.append(e.getText().toString());
String s = sb.toString();
try {
final String TESTSTRING = new String(s);
FileOutputStream fOut = openFileOutput("raksi.txt",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(TESTSTRING);
ll = TESTSTRING.length();
osw.flush();
osw.close();
}catch (Exception e) {
// TODO: handle exception
}
}
});
The following code is the click listener for the button get. it reads the data from the file and displays as toast,
Button b1 = (Button)findViewById(R.id.but1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
FileInputStream fIn = openFileInput("name.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[ll];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
Toast.makeText(getApplicationContext(), readString, Toast.LENGTH_LONG).show();
}
catch(IOException e){
// TODO: handle exception
}