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.
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();
I have created an app which allows user to create a note and save it.
i know the data is stored in the private storage area of the application but i need to actually view the file in which it is stored on through its file path. can anyone assist on how i can do this please? i have used the FileOutputStream and FileInputStream method
public class Utilities {
public static final String FILE_EXTENSION = ".bin";
public static boolean saveNote(Context context, Notes notes){
String fileName = String.valueOf(notes.getDateTime()) + FILE_EXTENSION;
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = context.openFileOutput(fileName, context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(notes);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
return false; //tell the user something went wrong
}
return true;
}
public static ArrayList<Notes> getSavedNotes(Context context) {
ArrayList<Notes> notes = new ArrayList<>();
File filesDir = context.getFilesDir();
ArrayList<String> noteFiles = new ArrayList<>();
for(String file : filesDir.list()) {
if(file.endsWith(FILE_EXTENSION)) {
noteFiles.add(file);
}
}
FileInputStream fis;
ObjectInputStream ois;
for(int i = 0; i < noteFiles.size(); i++) {
try{
fis = context.openFileInput(noteFiles.get(i));
ois = new ObjectInputStream(fis);
notes.add((Notes)ois.readObject());
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
return notes;
}
public static Notes getNoteByName(Context context, String fileName) {
File file = new File(context.getFilesDir(), fileName);
Notes notes;
if(file.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = context.openFileInput(fileName);
ois = new ObjectInputStream(fis);
notes = (Notes) ois.readObject();
fis.close();
ois.close();
} catch(IOException | ClassNotFoundException e){
e.printStackTrace();
return null;
}
return notes;
}
return null;
}
public static void deleteNote(Context context, String fileName) {
File Dir = context.getFilesDir();
File file = new File(Dir, fileName);
if(file.exists()) {
file.delete();
}
}
}
File Variables have a method named "getAbsolutePath" that will give you the path of file
For example when you declare a variable as File like this :
File filesDir = context.getFilesDir();
Then you can use this method to get the file path like this :
filesDir.getAbsolutePath();
You won't able to see that file physically on to the device because that get stored in internal memory of application.
Only your application can access that file.
To visualize/explore that file you need rooted device.
Android studio is having capability of file explorer,
Tools Menu > Android > Android Device Monitor
but you will able to see public folder structure.
The answer provided by Mahmood is correct.
To retrive file path you can use below function.
File filesDir = context.getFilesDir();
String filePath = filesDir.getAbsolutePath();
All the files will get stored in that location.
Hopefully this answer will help you.
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
}
I'm trying to store a Map into android's internal storage.
My code:
private void saveFavorite(){
LinkedHashMap<String, LinkedList<MyCustomObject>> favorites = new LinkedHashMap<String, LinkedList<MyCustomObject>>();
try{
InputStream file = openFileInput(PATH);
BufferedInputStream buffer = new BufferedInputStream( file );
ObjectInput input = new ObjectInputStream ( buffer );
try{
Object o = input.readObject();
if(o instanceof LinkedHashMap<?, ?>)
favorites = (LinkedHashMap<String, LinkedList<MyCustomObject>>)o;
}
finally{
input.close();
}
}
catch(ClassNotFoundException ex){
}
catch(IOException ex){
}
String favoriteName = "asd";
favorites.put(favoriteName, myobject);
FileOutputStream fos;
try {
fos = openFileOutput(PATH, MODE_APPEND);
BufferedOutputStream buffer = new BufferedOutputStream( fos );
ObjectOutput output = new ObjectOutputStream( buffer );
try{
output.writeObject(favorites);
}finally{
output.close();
}
}catch(IOException ex){
}
}
MyCustomObject implements Serializable
While debugging I don't see any problem. It seems it reads an empty map, then writes the map with a value but when I read it again, map is empty.
Help please.
UPDATE:
I have found inside /data/data/my_project_package_structure/files/
a file called like my var PATH. It's growing in size each time I call my save method so I think it writes well but I don't know what I'm doing wrong.
try {
**fos = openFileOutput(PATH, MODE_APPEND);**
BufferedOutputStream buffer = new BufferedOutputStream( fos );
Should be
**fos = openFileOutput(PATH, MODE_PRIVATE);**