Writing files internally - android

Within my app I am trying to write a file, which I can then internally read from.
Would anyone have an example of how to write files to the installation folders of app?

use the following code to write from Edittext into file and read from file into Edittext
set the following permission to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
JAVA CODE
EditText LoadedText;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadedText=(EditText) findViewById(R.id.LoadedText);
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File("/sdcard/RouterSetup.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
LoadedText.setText(text.toString());
}
public void saveFile() {
try {
File myFile = new File("/sdcard/RouterSetup.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(LoadedText.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD " + LoadedText.getText() + ".txt",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
getFilesDir() vs Environment.getDataDirectory()
public File getFilesDir ()
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
public static File getExternalStorageDirectory ()
Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().
If you want to get your application path use getFilesDir() which will give you path /data/data/your package/files
You can get the path using the Environment var of your data/package using the
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath(); which will return the path from the root directory of your external storage as /storage/sdcard/Android/data/your pacakge/files/data
To access the external resources you have to provide the permission of WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

The simplest solution is
String filename = "stuff.xml";
READ
FileInputStream stream = ctx.openFileInput(filename);
(and below is a really simple example of parsing that file)
BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = buffReader.readLine()) != null) {
...
// do something cool
...
}
} catch (IOException e) {
Log.e("MyApp", "SCREAAAAAM", e);
}
WRITE
OutputStreamWriter outputStreamWriter = new OutputStreamWriter( ctx.openFileOutput(filename, Context.MODE_PRIVATE) );
outputStreamWriter.write("this is text not xml :(");
So the two main things to note are the openFileInput and openFileOutput methods of Context (ie your activity) which take care of the heavy lifting

//here i am downloading file from server and writing
String download_link = "some server location";
URL url = new URL(download_link);
HttpsURLConnection c = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
c = (HttpsURLConnection) url.openConnection();
c.setHostnameVerifier(DO_NOT_VERIFY);
}
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "Mobi.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
you need to add permission in manifest file:
uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

Which type of files you are talking about ?
For data storage you can use shared preferences.
For media type you can use media storage.

Related

Reading txt file from Internal storage returns FIleNotFound even file is present at the address

i am trying to read file from internal storage. the file is available in internal storage at given location and the code is able to access it.. but when it tries to open the file , it throws FileNotFound Exception which is due to the app can't open the file to read. I came to know about the app can't open the file by using file.canRead() method which is returning false. can anybody help me to figure the situation out? Here is my code
path = MainActivity.this.getFilesDir().getAbsolutePath();
try {
File file = new File(path, "jamshaid.txt");
Context ctx = getApplicationContext();
FileInputStream fileInputStream = ctx.openFileInput(file.getName());
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String lineData = bufferedReader.readLine();
view1.setText(lineData);
} catch (Exception e) {
e.printStackTrace();
}
Permissions
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
API Version of my device is 24
What i wanna do?
i am trying to parsethe file/set text file data to textView
Update1
after changing
File directory = MainActivity.this.getFilesDir();
File file = new File(directory, "jamshaid.txt");
i am getting the following error
`09-25 14:45:16.413 21144-21144/com.example.root.testingvolley W/System.err: java.io.FileNotFoundException: /data/user/0/com.example.root.testingvolley/files/jamshaid.txt (No such file or directory)`
Try this for directory path
File directory = context.getFilesDir();
File file = new File(directory, filename);
Or
public String getTextFileData(String fileName) {
StringBuilder text = new StringBuilder();
try {
FileInputStream fIS = getApplicationContext().openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIS, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
text.append(line + '\n');
}
br.close();
} catch (IOException e) {
Log.e("Error!", "Error occured while reading text file from Internal Storage!");
}
return text.toString();
}
How are you verifying that the file exists? Perhaps the file does not exist, in which case openFileInput() will throw FileNotFoundException.
You can try opening the file in write-mode which will create a file if no such file exists.
FileOutputStream fileOutputStream = ctx.openFileOutput(file.getName(), ctx.MODE_PRIVATE);

Android, how to prevent internal storage files to be deleted when the app is uninstalled

I'm developing an app which stores few setting in two .xml files, saved on internal storage. I need to save them in there, so please don't answer me "Save them on SD-cards".
I try to uninstall an then re-install (from Android Studio) my app to see if the android:allowBackup="true" works also for internal stored file but the answer was no.
Is this because I done the re-install from the IDE or I need to add some code somewhere?
Thanks for help.
Starting API level 29 there is the "hasFragileUserData" manifest flag
The documentation states that
If true the user is prompted to keep the app's data on uninstall.
May be a boolean value, such as "true" or "false".
Sample code:
<application
....
android:hasFragileUserData="true">
You can save those file using Environment.getExternalStorageDirectory() This stores on the external storage device. Dont get confused with the term external storage as the SD card. SD card is the secondary external storage. But Environment.getExternalStorageDirectory() returns top-level directory of the primary external storage of your device which is basically a non removable storage.
So the file path can be /storage/emulated/0/YOURFOLDER/my.xml
So even if you uninstall the app, these files will not get deleted.
You can use this snippet to create a file in your primary external storage:
private final String fileName = "note.txt";
private void writeFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Save to: " + path);
String data = editText.getText().toString();
try {
File myFile = new File(path);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(), fileName + " saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Don't forget to add below permission in Android Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
You can then read that file as below:
private void readFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Read file: " + path);
String s = "";
String fileContent = "";
try {
File myFile = new File(path);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((s = myReader.readLine()) != null) {
fileContent += s + "\n";
}
myReader.close();
this.textView.setText(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), fileContent, Toast.LENGTH_LONG).show();
}

Android internal storage file writing is not working

I am new to android development. I've tried to write a file with a number in my android device . I could store the file in internal storage but I couldn't write on this file at this time.
This is my code .
Have any suggestions reveal to me.
int count=0;
FileOutputStream outputStream;
BufferedReader input=null;
File file=new File(getCacheDir(),"example.txt");
if(file.exists()==true){
try {
input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
StringBuilder builder=new StringBuilder();
while((line=input.readLine())!=null){
builder.append(line);
}
String g=builder.toString();
Toast.makeText(getApplicationContext(),"Count - " + g,Toast.LENGTH_LONG).show();
}catch (IOException e){
}
}else {
try {
count=count+1;
outputStream = new FileOutputStream(file);
outputStream.write(count);
outputStream.close();
Toast.makeText(getApplicationContext(),"File - "+file.getPath().toString(),Toast.LENGTH_LONG).show();
}catch (IOException e){
Toast.makeText(getApplicationContext(),"Error creating this file",Toast.LENGTH_LONG).show();
}
}
Thanks
Add this line in Your AndroidManifest.xml File
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Thanks everyone , I found a solution for my problem. I can do above work using a Sting instead of a integer. See you soon bye.

Create file from assets and get its path

I want to display a PDF stored in the assets folder using an external library. This library requires a path to a file.
I read that the pdf stored in the assets folder is not stored as a file. What I need is
Read the pdf-file from the assets into a (temporary) file object
get the path of that object for the external pdf-viewer-library
What I got so far is the following:
stream = getAssets().open("excerpt.pdf");
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
I'm not really sure what to do next unfortunately...
EDIT:
I tried the following code:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String dirout= Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ;
File outFile = new File(dirout, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
...
I am getting an exception in "out = new FileOutputStream(outFile);" (no such file or directory). I thought the code create a file there?
Does the directory exists?
If not, it will send an IOException.
Just to make sure, try this approach:
final File directory = new File("/sdcard/X/Y/Z/");
if (!directory.exists()) {
directory.mkdirs();
}
It will create the parent directories if they don't exist. If they exist, it will return false and it will NOT delete the content in it. After this, just continue the same way you were doing it.
File outFile = new File(directory, filename);
Don't forget to add the permissions to your AndroidManifest!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Copy the file to a public location that other applications can access using a process similar to that described in this question.
Keep a reference to the external file you created for launching your Intent(Intent.ACTION_VIEW).
Build an Intent to view your pdf, ex:
public void viewPdf(File YOUR_PUBLIC_FILE_FROM_STEP_1) {
PackageManager packageManager = getPackageManager();
Intent viewPdf = new Intent(Intent.ACTION_VIEW);
viewPdf.setType("application/pdf");
List<ResolveInfo> list =packageManager.queryIntentActivities(viewPdf,PackageManager.MATCH_DEFAULT_ONLY);
// Check available PDF viewers on device
if (list.size() > 0) {
Intent from_external_app = new Intent(Intent.ACTION_VIEW);
from_external_app.setDataAndType(Uri.fromFile(YOUR_PUBLIC_FILE_FROM_STEP_1),
"application/pdf");
from_external_app.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(from_external_app);
}

trying to open the sdcard's .txt file in my EditText

I am trying to open the sdcard's .txt file in my EditText to change the text in it and
save the changes using button click but its not going in right way .May I know what is the correct way to achieve my objective?
try this one..
you must set permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "followed by ur file dir");
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "sdcard.txt");
for (File wavfile : f.listFiles())
{
String str = wavfile.getName().toString();
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/sdcard/"+filename);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
edtitext.setText(aBuffer.tostring());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext
(),aBuffer,Toast.LENGTH_LONG).show();
}
}
again btnclick you have to write that edited string right..
use this one for write in that file..
FileOutputStream fos;
try {
File myFile = new File("/sdcard/"+sdcard.txt);
myFile.createNewFile();
FileOutputStream fOut = new
FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new
OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(),filename + "
saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
thank you...
more detalis ref this link'
http://www.javatpoint.com/android-external-storage-example
----------------------------------------------------------
Some manufacturers (mainly Samsung) give write permissions only to the internal storage mounted at /storage/sdcard.
Also you should enable your app to write to external storage by adding this permission in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
First try to read the complete text file and save the text in a string.
For that you can refer this link
When you read the complete text file and get the text in a string, set the string to the editText by
edtitext.setText(your string);

Categories

Resources