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();
Related
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 am new to android development. Currently, i am developing a simple app for writing and reading a String Array to an internal storage.
First we have A array then save them to storage, then next activity will load them and assign them to array B. Thank you
To write to a file:
try {
File myFile = new File(Environment.getExternalStorageDirectory().getPath()+"/textfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.write("replace this with your string");
myOutWriter.close();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
To read from the file:
String pathoffile;
String contents="";
File myFile = new File(Environment.getExternalStorageDirectory().getPath()+"/textfile.txt");
if(!myFile.exists())
return "";
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
int c;
while ((c = br.read()) != -1) {
contents=contents+(char)c;
}
}
catch (IOException e) {
//You'll need to add proper error handling here
return "";
}
Thus you will get back your file contents in the string "contents"
Note: you must provide read and write permissions in your manifest file
If you wish to store yourObject to cache directory, this is how you do it-
String[] yourObject = {"a","b"};
FileOutputStream stream = null;
/* you should declare private and final FILENAME_CITY */
stream = ctx.openFileOutput(YourActivity.this.getCacheDir()+YOUR_CACHE_FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream dout = new ObjectOutputStream(stream);
dout.writeObject(yourObject);
dout.flush();
stream.getFD().sync();
stream.close();
To read it back -
String[] readBack = null;
FileInputStream stream = null;
/* you should declare private and final FILENAME_CITY */
inStream = ctx.openFileInput(YourActivity.this.getCacheDir()+YOUR_CACHE_FILE_NAME);
ObjectInputStream din = new ObjectInputStream(inStream );
readBack = (String[]) din.readObject(yourObject);
din.flush();
stream.close();
On Android you have several storage options.
If you want to store a string array, use SharedPreferences:
This post might be a solution.
So, my app receives a large xml from a soap server. I wish to save this in a file, for later use. I managed to do this, and to read the file. BUT the result (after reading) is a garbled xml! A large portion of text (412 characters) from the latter part of the xml is copied and pasted at the end of my xml, and I can't figure out why this is happening.
I have tried 2 ways to write the file and 2 ways to read the file, no dice! (will post code below) Note: xml is large 5000-20000 characters, so I used methods to keep eclipse from returning out of memory error.
BOTTOM LINE:
-input xml file is correct
-output xml file is incorrect
-tried 2 save methods
-tried 2 read methods
-wtf?!
save code 1:
InputStream is = new ByteArrayInputStream(string.getBytes());
FileOutputStream fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))>0){
fos.write(buffer, 0, length);
}
fos.flush();
fos.close();
is.close();
save code 2 :
InputStream is = new ByteArrayInputStream(string.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
FileOutputStream fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
Log.e("stuff is good", "line: "+line);
sb.append(line);
if (sb.toString().length() > 10000) {
fos.write(sb.toString().getBytes());
fos.flush();
sb = new StringBuilder();
}
}
fos.write(sb.toString().getBytes());
fos.flush();
is.close();
fos.close();
read code 1:
FileInputStream fis = openFileInput("caca");
int c;
StringBuilder fileContent = new StringBuilder();
while((c=fis.read())!=-1)
{
fileContent.append((char)c);
}
fis.close();
Log.e("TEST TEST", "XML length = "
+String.valueOf(fileContent.length()) );
Log.e("TEST TEST", "XML = "
+fileContent );
read code 2 :
FileInputStream fis;
fis = openFileInput("caca");
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
int i =1;
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
Log.v("TEST"+ String.valueOf(i), new String(buffer) );
i++;
}
Log.e("TEST TEST", "XML length = "
+String.valueOf(fileContent.length()) );
Log.e("TEST TEST", "XML = "
+fileContent );
save to file code :
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(fileContent);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
Sorry for the long post, but after 3 days, I'm at my wits end. Any input would be nice, thank you!
I prefer to use Apache Commons IO for this:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url + id);
try {
HttpResponse response = client.execute(httpGet);
InputStream content = response.getEntity().getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(content, writer, "utf-8");
return writer.toString();
} catch (ClientProtocolException e) {
Log.e(tag, "client problem:" + e.getMessage());
throw new RuntimeException("client problem",e);
} catch (IOException e) {
Log.e(tag, "IO problem:" + e.getMessage());
throw new RuntimeException("IO problem",e);
}
Then just write out the string as usual.
ok.... I fixed it , I have no idea why it works.
save code:
public static void Save(String filename, String string,
Context ctx) {
Log.e("stuff is good", "xml length b4 save= "+String.valueOf(string.length()));
try {
FileOutputStream fOut = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(Login.messagesXmlDump);
myOutWriter.close();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
read code:
Save("LOL", messagesXmlDump, getApplicationContext());
try {
FileInputStream fis = openFileInput("LOL");
int c;
StringBuilder fileContent = new StringBuilder();
while((c=fis.read())!=-1)
{
fileContent.append((char)c);
}
fis.close();
Managed to write/read a 70k characters long xml. Maybe that recursive method of saving it wasn't the best idea. Think I over-complicated a simple matter.
Sorry for wasting your time :(
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)
{}
}
}
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
}