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
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 am working on an app where I want to be able to export and import some data from the app, on a .txt file.
The minimum API of the app is 21.
The export part works well, but I am having trouble with the import part.
I open the file explorer :
butImportPatient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
startActivityForResult(intent, IMPORTPATIENT_ACTIVITY_REQUEST_CODE);
}
});
This looks like it is working.
But my onActivityResult doesn't work, I didn't find how I can get the file from the Uri.
For now, here is my code :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMPORTPATIENT_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
File file = new File(data.getData().getPath()) ;
String path = file.getAbsolutePath() ;
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append("\n");
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this) ;
builder.setMessage(path)
.show() ;
}
}
It is a mix of multiple posts I saw here, but none seems to work.
I get this path :
/document/home:List.txt
It creates FileNotFoundException. How can I get the real path of the file ?
I didn't find how I can get the file from the Uri.
There is no file. ACTION_OPEN_DOCUMENT and ACTION_GET_CONTENT do not open a file. They open a document. That document might be a file. It might not.
That Uri might point to:
A local file on external storage
A local file on internal storage for the other app
A local file on removable storage
A local file that is encrypted and needs to be decrypted on the fly
A stream of bytes held in a BLOB column in a database
A piece of content that needs to be downloaded by the other app first
...and so on
How can I get the real path of the file ?
You don't.
If you wish to only accept files, integrate a file chooser library instead of using ACTION_OPEN_DOCUMENT or
ACTION_GET_CONTENT. Just bear in mind that filesystem access to external storage is limited on Android 10+.
If you use ACTION_GET_CONTENT, and the scheme of the Uri that you get is file, then getPath() will be a filesystem path.
Otherwise, you need to understand that you have no idea where the document is coming from, and stop thinking in terms of "real path of the file". Use ContentResolver and openInputStream() to make a copy of the content to some file that you control, then work with that file.
I have a file which is "content.txt". At the first, if the file doesn't exists, I will create it and write the detail in the file as
"123,abc"
Then If I want to update the "abc" to "abcd". I used below code. Now, my issue is that If I want to add more line which does not equal first field "123", then it will append in the file. However, it does not append in my file. What is happend in my code? Could you help me to fix it
This is example. First my file is empty. I put the String "123,abc" then the content in the file is
123,abc
Then I insert "abcd" to update the its second field. The content of file is
123,abcd
Now, I insert a new field 456,xyz which does not equal 123 then the file is
123,abcd
456,xyz
This is my code
String whole_content="123,abc";
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+ "/" + "content.txt" ;
boolean flagdataempty=false;
File file = null;
try {
file =new File(filename);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
flagdataempty=true;
}
} catch (IOException e) {
e.printStackTrace();
}
String tempFilename=filepath+"/" + "content_temp.txt";
File tempFile = new File(tempFilename);
BufferedReader reader = null;
BufferedWriter writer =null;
boolean flagsearch=false;
try {
reader = new BufferedReader(new FileReader(file));
writer=new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null) {
flagdataempty=false;
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String[] separated = trimmedLine.split(",");
String classID_out = separated[1].trim(); // this will contain data
if(classID_out.equals("abc"))
{
currentLine=separated[0].trim()+","+"abcd";
writer.write(currentLine + System.getProperty("line.separator"));
flagsearch=true;
}
else
writer.write(currentLine + System.getProperty("line.separator"));
}
if(flagdataempty|!flagsearch) {
writer.write(whole_content + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(file);
Update: I done by using flag. It will set true if I find 123. Otherwise,I will write the new line. Thanks
I don't see the code actually trying to write the content you want to write, but give following code a try, as you want to add next text which does not contain 123 to the next line.
if(classID_out.equals("abc"))
{
currentLine=separated[0].trim()+","+"abcd";
writer.write(currentLine + System.getProperty("line.separator"));
}else{
Files.write(Paths.get("filepath+ "/" + "content.txt"), "\n456,xyz".getBytes(), StandardOpenOption.APPEND);
}
I would not recommend this kind of fashion to read and write data which would change over the time and you constantly will have a lot of hustle reading and writing the data to it,
the Best way would be is to write JSON or XML of a serialized way to the text file. it will remove the headache of dealing with low level functions as you would have your object populated thought GSON or Simple XML Framework.
In a case I would suggest have a ArrayList of object which will be written to the text file, read the text file and populate your ArrayList from that, and then try adding something to the arraylist, if it already exist it wont add to the arrylist and if does not exist it will add to the arrylist, after your work is done with the Arraylist, write that to the text file again
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
Is it possible to open a .txt file or show the content of the .txt file in activity? I really need it for my project. In my project I'm making the expandablelistview which shows the unit at the parentlist and chapter in childlist. Once the child is selected the selected child will open the appropriate .txt file. Is it possible to do so. Please give some suggestions on it.
You can Have TextView to show text in Activity, to set text on TextView use method setText(CharSequence) method.
To Read Text from .txt file, use Following method:
FileInputStream fis=null;
final StringBuffer buffer= new StringBuffer();
try {
fis = openFileInput("fileName.txt");
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
if ((strLine = dataIO.readLine()) != null) {
buffer.append(strLine);
}
dataIO.close();
fis.close();
}
catch (Exception e) {
}
Use
textView.setText(buffer.toString());
to show in Activity.
Yes.
You just need a File and read it. Just use the Commons IO library from apache.org
//file located directly on SD root.
File myFile = new File(Environment.getExternalStorageDirectory(), "file.txt");
String contents = FileUtils.readFileToString(myFile);
After that just use something like myTextView.setText(contents); to set the text to a TextView.
Download Commons IO library here.
i think showing an xml file with a textview in it and setting up the textview to show whatever you want to show will do the trick.
textview.setText(open file you want to read from here);
to open a file you should use the Buffered reader and IO streams.