I am trying to create a .txt file in android, I have tested a lot of options how to achieve this, I think the file is created but I can't find it, it should be writed somehow public in a public directory that I can access it.
Example:
cacheFile = new java.io.File(getFilesDir(), "cache.txt");
if(cacheFile.exists() && !cacheFile.isDirectory()) {
try {
writer = new FileWriter(cacheFile);
BufferedReader br = new BufferedReader(new FileReader(cacheFile));
String tempo;
while((tempo = br.readLine()) != null){
Log.i("TEST","Reading from cache "+tempo);
if (tempo.contains("http")) {
musicUrl.add(tempo);
}
else {
myDataList.add(tempo);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
else {
try {
Log.i("TEST", "Creating the cache ? " + cacheFile.createNewFile() + " in " + getFilesDir());
writer = new FileWriter(cacheFile);
} catch (IOException e) {
e.printStackTrace();
}
}
What other option I've tried: Android File on Internal Storage not found
you should use one of the following:
getExternalFilesDir()
getExternalStoargeDir()
the first will create a file in /sdcard/android/app.package/file
the second will be the root of /sdcard/
The call that you currently make, getFilesDir(), is returning the path in /data/data/app.package/file which is not accessable to anything other then your application.
Related
I a newbie in android development.
I sure that many people have same issue. I ve a Galaxy S7 phone without SD Card. So no external storage. But i want create file with my app which have to be access from windows explorer to export it.
Note : debbug in USB mode - No virtual device
Of course in my manifest file i ve setted those 2 permissions :
android.permission.WRITE_INTERNAL_STORAGE
android.permission.WRITE_EXTERNAL_STORAGE
To be sure i ve created a file i use this write method and the following read method :
File root = this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File customFolder = new File(root.getAbsolutePath() + "/CustomFolder");
customFolder.mkdirs();
file = new File(customFolder, "myData.txt");
// Must catch FileNotFoundException and IOException
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Howdy do to you,");
pw.println("and the horse you rode in on.");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "File not found");
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "I/O exception");
}
To read myData.txt
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while (true) {
line= br.readLine();
if (line== null) break;
tv.append("\n" + " " + line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
So all method are OK, but when i browse my files system to get the created file myData.txt, I can't find it !!
Most of the apps we install have their own folder on the root, like Snapchat, Whatsapp etc etc
I d like to make the same thing, what is the way to write file in:
ROOT --> MyApplicationName --> CustomFolder
Thanks for your help :)
I finally found a solution adding a MediaScannerConnection.scanFile() method.
MediaScannerConnection.scanFile(getApplicationContext(),new String[]{file.getAbsolutePath()},null,new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
// Do something here if you want
}});
But this solution don't totally fit me, because the storage folder is :
Android/data/donain_name/files/Documents/CustomFolder
I'd like to have same result like whatsapp application which can have a folder in the internal storage root.
The result i want is :
MyApplication/CustomeFolder
I must transfer a data file necessary for my app.
I read many threads on the subject and I stll don't understand how it works.
1. I'm using android studio 0.8.6. A lot of threads mentions the folder assets which apparently resides in src/main. When I create a new project the folder doesn't exist. I create manually one and I put in it jpg and txt files.
2. I run the following code:
AssetManager am = getAssets();
String[] files = new String[0];
try {
files = am.list("Files ;
} catch (IOException e) {
e.printStackTrace();
}
for(int i=0;i<files.length;i++){
Toast.makeText(getApplicationContext(), "File: "+files[i]+" ", Toast.LENGTH_SHORT).show();
}
And I get a files.length = 0
1. I can create files, write in it and read it but I don know where they reside.
And that's not what I want to do. I want to pass the data with the app.
Sorry for the long email but I'm lost.
Thanks in advance!
The code I have used to read files from assets is listed below:
public String ReadFromfile(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
This code is not mine and can be found in the answers below:
read file from assets
I did some progress using the following code:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
File dir = getFilesDir();
File f = new File("/data/data/com.example.bernard.myapp/");
File file[] = f.listFiles();
for(int i=0;i<file.length;i++){
Toast.makeText(getApplicationContext(), "File: "+String.valueOf(file[i]), Toast.LENGTH_SHORT).show();
}
}
I code in hard what seems to me like the root of my app:
File f = new File("/data/data/com.example.bernard.myapp/");
The result is I can see 3 files: lib, cache, files
in "files" appears the files I create running the app.
I still don't know where is assets, neither where I transfer/put the .txt and .jpg files I want to use with my app. I develop using studio.
I'm trying to read a file created by another Android application.
File file = new File("/data/data/air.br.com.screencorp.MobilePlayer/br.com.screencorp.MobilePlayer/Local Store/token");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
Log.d("SIZE", "Total file size to read (in bytes) : "
+ fis.available());
int content;
StringBuilder token = new StringBuilder();
while ((content = fis.read()) != -1) {
token.append((char) content);
}
Log.d("TOKEN", token.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
I don't know why, but I'm not allowed to access that file. I have the READ_EXTERNAL_STORAGE permission on my manifest.
Should I use SharedPreferences?
Thanks.
Data of other applications private data can not be accessed from your app. This is the security model of android. The app should have set MODE_WORLD_READABLE permission on the file, only then can you access the file
This question already has answers here:
How do I write the exception from printStackTrace() into a text file in Java?
(5 answers)
Closed 8 years ago.
My program is crashing in device. I want to exactly catch the log of my program while running in my device .i.e I want to write the log to my sd card, up to the point of crashing. How can I achieve this?
Try this
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this)); // add this to your activity page
public class ExceptionHandler implements
java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
private final String LINE_SEPARATOR = "\n";
UncaughtExceptionHandler defaultUEH;
public ExceptionHandler(Context con) {
myContext = con;
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
#SuppressWarnings("deprecation")
public void uncaughtException(Thread thread, Throwable exception) {
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
StringBuilder errorReport = new StringBuilder();
errorReport.append("************ CAUSE OF ERROR ************\n\n");
errorReport.append(stackTrace.toString());
errorReport.append("\n************ DEVICE INFORMATION ***********\n");
errorReport.append("Brand: ");
errorReport.append(Build.BRAND);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Device: ");
errorReport.append(Build.DEVICE);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Model: ");
errorReport.append(Build.MODEL);
errorReport.append(LINE_SEPARATOR);
File root = android.os.Environment.getExternalStorageDirectory();
String currentDateTimeString = DateFormat.getDateTimeInstance().format(
new Date());
File dir = new File(root.getAbsolutePath() + "/dir_name/log");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "log.txt");
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(currentDateTimeString + ":" + errorReport.toString());
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
defaultUEH.uncaughtException(thread, exception);
System.exit(0);
}
}
Once I got this from somewhere in SO. Try this:
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -f "+ filename + " -v time *:V";
Log.d(TAG, "command: " + command);
try{
Runtime.getRuntime().exec(command);
}
catch(IOException e){
e.printStackTrace();
}
}
This prints log continuously until the app exit.
Try this :
public void appendLog(String text) {
File logFile = new File("sdcard/log.file");
if (!logFile.exists()) {
try {
logFile.createNewFile();
}
catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
If you want to catch only the exception with the stacktrace, which in most cases is enough to get what was wrong, then ACRA is a winning solution.
If you do want to write something to your SD card then take in consideration that you can't assume that any device has external storage that you can write to. Unless you validate this.
To bring another option of writing to external storage you can use this simple library:
android-simple-storage
This is how you use it:
Prepare somewhere in your app:
Storage storage = SimpleStorage.getExternalStorage();
// create your own directory
storage.createDirectory("MyDir");
// create the file you want to write to inside your new directory
storage.createFile("MyDir", "MyFile.txt", "");
Append any string (or byte[]) whenever you want to this file:
storage.appendFile("MyDir", "MyFile.txt", "your log line");
You can create/read/update/delete with this tiny library files on internal and external storages very easy. And, take into consideration that writing to the same file will increase the space it takes. You can use getSize() from the same library to validate.
Hy!!
I have a login form in my app, but i want to save/restore the textfile internal in the app not on the internal phone memory.
Are there some code snippets?
I made a internal file saving/restoring but it don't work.
if (cb.isChecked())
{
File file = new File("/mmt/sdcard/login.skip");
Writer output = null;
try
{
output = new BufferedWriter(new FileWriter(file));
output.write(etuser.getText().toString()+ ";" + etpw.getText().toString());
output.close();
}
catch (Exception e) {
// TODO: handle exception
}
}
File file = new File("/mmt/sdcard/login.skip");
if(file.exists())
{ try
{
BufferedReader input = new BufferedReader(new FileReader(file));
while (( line = input.readLine()) != null){
line2 = line;
}
etuser.setText(line2.split(";")[0]);
etpw.setText(line2.split(";")[1]);
input.close();
}
catch (Exception e) {
// TODO: handle exception
}
}
Edit: See Internal Storage
Alternative,
Use SharedPreference It'll be Private to you're Application. And cannot be accessed otherwise. (For a non-rooted phone, atleast)