I am developing in Android , I found a sample code and it read and write the data to the txt file like the following code:
The following function is for writing data to text file:
private static final String MESH_DATA_FILE_NAME = "TEST.txt";
public void save(Activity activity) {
try {
int i;
Context context = activity;
FileOutputStream fos = activity.openFileOutput(MESH_DATA_FILE_NAME, context.MODE_PRIVATE);
String str;
for (i = 0; i < 10; i++) {
str += "##" + i;
}
fos.write(str.getBytes());
fos.write('\n');
fos.close();
} catch (Exception e) {
Log.e(TAG, "saveMeshInfo exception: " + e);
}
}
The following code for reading data from text file:
public void read(Activity activity) {
try {
FileInputStream fin = activity.openFileInput(MESH_DATA_FILE_NAME);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
Log.i(TAG, "From file [" + MESH_DATA_FILE_NAME + "]...");
// Read the information
String text = br.readLine();
String[] strs = text.split("##", 4 + FloodMesh.IV_LEN + FloodMesh.KEY_LEN);
fin.close();
} catch (Exception e) {
}
}
It can see the data from the log when it call read function , so the TEST.txt should be exists.
But I didn't found the TEST.txt via file manager app on my android phone.
Why I didn't found the TEST.txt file on my android phone ?
If the TEST.txt not exists , why the read function can read the data ?
How to find the TEST.txt file ?
You've created file in you app directory (/data/data/your.package) and you don't have access there via file manager. The file exists that is why you can read it via method but you won't see it. Test your code on emulator - than you will be able to see the file
If you want to test it better and you don't want to use emulator you can save file on sdcard, you have access there via file manager and you will be able to see it
your file will be in /data/data/<your package name>/files/ - either you have root and an explorer to see this or you use the run-as command on adb to explore the file
With the right permission you can also write the file to sd-card - then accessing it is easier - depends on your needs
You didn't found the TEST.txt because it's in private mode, you need to write MODE_APPEND,You should check http://developer.android.com/reference/android/content/Context.html.
activity.openFileOutput() This method opens a private file associated with this Context's application package for writing. see doc
Related
I have to export files from my application and looking for a solution, where I can save files, to give the user the possibility to open them.
I tried already getFilesDir().getPath() which worked well, until I realized that the folder can't open from a real device (/data/user/0/com.myapplication.example/files) since the /data path is just a storage area for the application.
What are the alternatives?
You should have a look here https://developer.android.com/training/data-storage
I'm not sure what file type you are trying to store however what you have tried stores the file withing the applications directory and not the devices. To combat this I would look under either Media or Documents and other files again in the above link. I would be able to be of further assistance if I knew what file type you are trying to store. Hope this helps you in some way.
This is a function to store a float array to the phone external storage. Pass the file name.extension in the String name. You could modify it to export your file.
public static void save(float[] input_array, String name)
{
final String TAG2 = "->save()";
String string_array = Arrays.toString(input_array);
String fullName = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder/" + name;
String path = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder";
File folder = new File(path);
if(!folder.exists())
{
folder.mkdirs();
}
BufferedWriter buf;
try
{
buf = new BufferedWriter(new FileWriter(fullName));
buf.write(string_array,0,string_array.length());
buf.close();
Log.d(TAG+TAG2, "array saved as document. ");
}
catch (IOException e)
{
Log.e(TAG+TAG2, "problems while saving the file. ");
}
}
The suggestion with getExternalStorage().getPath() (Thanks to blackapps) helped me to save the pdf in a folder, which can be opened in the file manager.
I have an android app that is writing a values to a file that the app also creates. I am able to write to the file and then again read from the file. However, as soon as that activity is finished, it seems that the file is now gone, or loses it's values.
I know you can't browse the files through explorer unless you root your phone and/or run the adb server as a specific user.
Here is my code for writing to the file:
public void savePrices(View view) {
FileOutputStream outputStream;
File getFilesDir = this.getFilesDir();
File filePathOne = new File(getFilesDir, filename);
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
for (int i = 0; i < priceArray.length; i++) {
outputStream.write(String.format("%.2f\n", priceArray[i]).getBytes());
}
Toast.makeText(this, "Prices saved successfully!", Toast.LENGTH_SHORT).show();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Here is my code that reads the file:
public void loadPrices(View view) {
int i = 0;
final InputStream file;
BufferedReader reader;
try{
file = getAssets().open(filename);
reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while(line != null){
line = reader.readLine();
priceArray[i] = Double.parseDouble(line);
i++;
}
} catch(IOException ioe){
ioe.printStackTrace();
hamburgerPriceText.setText(String.format("%.2f", priceArray[0]));
hotDogPriceText.setText(String.format("%.2f", priceArray[1]));
chipsPriceText.setText(String.format("%.2f", priceArray[2]));
beerPriceText.setText(String.format("%.2f", priceArray[3]));
popPriceText.setText(String.format("%.2f", priceArray[4]));
Toast.makeText(this, "Prices loaded successfully!", Toast.LENGTH_SHORT).show();
}catch (NumberFormatException e) {
Log.e("Load File", "Could not parse file data: " + e.toString());
}
}
After I call the save method which sets the values in the array and saves the values to the file, I run a clear method that removes all the values on the activity fields and in the array. So when I run the read method and it populates the fields on the activity, I know the values are coming from reading the file. This is the only way that I know that I'm saving and reading from the file successfully.
My question is how do I make it permanent? If I close the activity that saves the values and then immediately run the read method, all the values are 0.
Is there something that I am missing? How can I write to a file so if the activity is closed, or the app is completely closed, I can still retain the values?
Here is my code that reads the file:
There is nothing in that code that reads a file. It is reading some stuff out of the your app's assets. Also, for some reason, it is only updating the UI if you have an exception.
So when I run the read method and it populates the fields on the activity, I know the values are coming from reading the file.
No, they are coming from your app's assets, and you are only populating the fields if you have an IOException.
My question is how do I make it permanent?
Step #1: Actually read from the file. Since you are using openFileOutput() to write to the file, use openFileInput() to read from the file.
Step #2: Update the UI when you successfully read in the data, not in the catch block for the IOException.
I have saved a file with .docx extension in my app.the file is saved in the sdcard. The file appears as a word file in my sdcard but I am unable to open it (using polaris or any other default software) and message"unsupported file" appears.
When I save the file with .txt extension, I can open it.
public void Savedoc(View v)
{
String filename = "file" + sn + ".docx";
String filepath = "MyFileStorage";
myExternalFile = new File(getExternalFilesDir(filepath), filename);
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(ly.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
thank you alexandru ...but now i get an error message on running the app stating "The Javadoc for this element could neither be found in the attached source nor the attached Javadoc".pls help...
You'll need to use Apache POI in order to correctly create a .docx file.
I've found this answer with a code snippet:
XWPFDocument document = new XWPFDocument();
XWPFParagraph tmpParagraph = document.createParagraph();
XWPFRun tmpRun = tmpParagraph.createRun();
tmpRun.setText("LALALALAALALAAAA");
tmpRun.setFontSize(18);
document.write(new FileOutputStream(new File("yourpathhere")));
You may find more information about how to use XWPF here.
I've been trying to do some research and learn android. I do not understand what the following code does.
public class LogFile extends Activity {
private final static String STORETEXT = "storetext.txt";
private TextView write log;
public void readFileInEditor() {
try {
InputStream in = openFileInput(STORETEXT);
if (in != null) {
InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(tmp);
String str;
StringBuilder buf = new StringBuilder();
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
in.close();
writelog.setText(buf.toString());
}
} catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
I don't understand how this method works. Is it reading a file that is referenced with STORETEXT? If it making a file, where is this file saved? And finally, how can I access the "storetext.txt" file so that I may send it using
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/path/to/file")));
in an email attachment? Thanks for helping me learn, I've been trying to do some research on this but I am having trouble understanding this concept. Any help is appreciated.
openFileInput() is used so the file resides in the app specific internal files dir. Use getFilesDir() to find the directory and then add the filename. But.... Other apps have no access to this private directory. So you first have to copy the file to a place where other apps have access.
This code is reading in a text file "storetext.txt" and then displaying the content of the file in a text view.
The InputStreamReader reads the file and the BufferedReader and the StringBuilder work together to create a long string that has all the contents of the file.
How you access this file to sent with an Intent will depend on where the file is. Is it outside of your app environment, like on the SD card? Or is it in a resource folder like res/raw/storetext.txt?
You'll have to use different methods of getting a reference to your file depending on the situation. Do you know where the file is?
Also, if you are looking to send a file using the intent
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/path/to/file")));
and the file you are trying to send is in the apps private directory, you must use a ContentProvider in order to let other apps(like the native email app) access your file that you wish to send.
Here's a link that was very helpful in helping me figure that out.
http://stephendnicholas.com/archives/974
Hallo,
Here's some code which writes a data class to a file, then checks to see that the file exists. I can see that the file exists on the emulator, but file.exists() and therefore saveStateAvailable() returns false.
private void saveStateFile() {
/*DEBUG*/Log.d(this.getClass().getName(), "saveStateFile: Started");
mGameData = getGameData();
try {
FileOutputStream fileoutputstream = openFileOutput(mGameData.pilotName + STATE_FILE_EXTENSION, Context.MODE_WORLD_WRITEABLE);
ObjectOutputStream objectoutputstream;
objectoutputstream = new ObjectOutputStream(fileoutputstream);
objectoutputstream.writeObject(mGameData);
objectoutputstream.close();
fileoutputstream.close();
/*DEBUG*/Log.i(this.getClass().getName(), "saveStateFile: State saved to "+mGameData.pilotName + STATE_FILE_EXTENSION);
} catch (IOException e) {
/*DEBUG*/Log.e(this.getClass().getName(), "saveStateFile: Error writing data state file, "+mGameData.pilotName + STATE_FILE_EXTENSION);
e.printStackTrace();
}
/*DEBUG*/Log.d(this.getClass().getName(), "saveStateFile: Finished stateFileAvailable="+stateFileAvailable());
}
private boolean stateFileAvailable() {
File file = new File(mGameData.pilotName + STATE_FILE_EXTENSION);
/*DEBUG*/Log.d(this.getClass().getName(), "stateFileAvailable: Called ("+mGameData.pilotName + STATE_FILE_EXTENSION+" exists = "+file.exists()+")");
return file.exists();
}
Any ideas?
-Frink
You need to use Context#getFileStreamPath(String) where the String is the filename of the File object you are trying to access. Then you can call File#exists on that object. So:
File file = getFileStreamPath(mGameData.pilotName + STATE_FILE_EXTENSION);
Gives you access to the File object that points to the correct place in your private app storage area.
What your code is going atm is accessing the file /<your file name> which is on the root path. You file obviously does not exist there.