I am trying to write a text file to internal storage of my android application. But it is not possible for me to see if the file is generated or not.
My text file is stored in the following path:
data/data/"MyApplcationPackageName"/files/MyFile.txt
Permission : drwxrwx-x
I have tried the following things -
1) Using device file explorer:
Device file explorer does not open my application package. it gives following error if I try to open it.
Device File Explorer
2) Terminal:
I have also tried opening it using adb in the terminal. But when I try to open files inside my application package it says permission denied.
adb terminal
Please let me know how I can open my text file for debugging. Thanks in advance.
public static void StoreDB() {
if(isExternalStorageWritable() && checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
File file = getFinalDir();
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write("something".getBytes());
fos.close();
ToastUtil.showToast(Resource.getAppContext(),"File Saved");
} catch (IOException e) {
Log.e("StoreDB", "Exception");
e.printStackTrace();
}
}
}
public static boolean isExternalStorageWritable() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Log.d("External storage", "Writable");
return true;
}
Log.d("External storage", "Not Writable");
return false;
}
public static boolean checkPermission(String Permission){
int check = ContextCompat.checkSelfPermission(Resource.getAppContext(),Permission);
boolean Perm = (check == PackageManager.PERMISSION_GRANTED);
Log.d("Check Permission", "Result: " + Perm);
return Perm;
}
private static File getFinalDir() {
return createDirIfNotExist(Environment.getExternalStorageDirectory().getPath() + "/Co_Ordinate.txt/");
}
public static File createDirIfNotExist(String path) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
Now I am trying to put the file in external storage. Above code always gives IO exception.
You need to root your phone to view those files. Or you can do it on an emulator by using the Device File Explorer.
EDIT: Or just use an unprotected file path. This will create the directory. After that you just need to save the .txt file to that directory.
private static File getFinalDir() {
return createDirIfNotExist(Environment.getExternalStorageDirectory().getPath() + "/MyAppName/");
}
public static File createDirIfNotExist(String path) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}
You can do this with Emulator. Run your app in emulator and go to Android Device monitor
Choose device, go to File Explorer menu and search your text file in data folder
Related
I've finished an app and have been attempting to have that app log some data in a text file. I have a few questions about creating files and file paths with Android Studio. I'm not well versed in the editor so perhaps my questions are simple. I'm logging the data in an activity that extends MainActivity, declared as LoggerActivity.
public class LoggerActvitivty extends MainActivity{
public boolean bNewUser = true;
public String sFileName;
public void writeToFile(HashMap hmSaleToSave) {
if (bNewUser) {
System.out.println(hmSaleToSave);
sFileName = Environment.DIRECTORY_DOWNLOADS + "/Sales-" + LocalDateTime.now() + ".txt";
try {
if(!Files.exists(Paths.get(sFileName))) {
Files.createFile(Paths.get(sFileName));
Files.write(Paths.get(sFileName), sFileName.getBytes(StandardCharsets.UTF_8));
}
System.out.println("FILE WRITE EXECUTED");
System.out.println("Location" + sFileName);
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
}
}
Nothing crash's, but I believe I'm providing a null directory resulting in this logcat error
W/System.err: java.nio.file.NoSuchFileException: Download/Sales-2021-08-16T07:44:36.321.txt
I would like the logs to go to my tablets download directory. My first question is should I be using a different method to get my directory rather than through Enviornment.DIRECTORY_DOWNLOADS? Additionally if the path doesn't exist Files.createFile(....) should create the path too? Or does that just create the file at the specified path (sFileName)?
My app should save files to a place where, when you connect your phone/tablet to a computer, you can see them through the system file explorer.
This is the way I implemented file writing:
protected String mDir = Environment.DIRECTORY_DOCUMENTS;
protected File mPath = Environment.getExternalStoragePublicDirectory(mDir);
protected void writeLogFile(String filename) {
File f = new File(mPath, filename + ".txt");
f.getParentFile().mkdirs();
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f, false))) {
// Details omitted.
} catch (Exception e) {
e.printStackTrace();
return;
}
makeText("Wrote " + f.getAbsolutePath());
}
This is what I see when I connect my Sony Xperia Z4 tablet to Windows (notice missing documents folder):
This is the directory to which the file is written (using above implementation):
What is wrong with my implementation?
What is wrong with my implementation?
MediaStore has not discovered your newly-created files yet. What you see in Windows — and in many on-device "gallery" apps — is based on what MediaStore has indexed.
Use MediaScannerConnection and its scanFile() method to tell MediaStore about your file, once you have written out your data to disk:
public void scanFile(Context ctxt, File f, String mimeType) {
MediaScannerConnection
.scanFile(ctxt, new String[] {f.getAbsolutePath()},
new String[] {mimeType}, null);
}
or, in Kotlin:
fun scanFile(ctxt: Context, f: File, mimeType: String) {
MediaScannerConnection.scanFile(ctxt, arrayOf(f.getAbsolutePath()), arrayOf(mimeType), null)
}
I have created an auto-updater for my java program. but at the end of the download it downloads the file to desktop. I can to get where is the program file and update it?
this is my code:
#Override
public void run() {
if(!Debug) {
try {
FileUtils.copyURLToFile(new URL("fileurl"), new File(System.getenv("APPDATA") + "\\file.zip"));
UnzipUtility unzip = new UnzipUtility();
File deskfile = new File(System.getProperty("user.home") + "/Desktop/file.jar");
if(deskfile.exists()) {
deskfile.delete();
}
unzip.unzip(System.getenv("APPDATA") + "\\file.zip", System.getProperty("user.home") + "/Desktop");
File file = new File(System.getenv("APPDATA") + "\\file.zip");
file.delete();
Successfull = true;
} catch (IOException e) {
Successfull = false;
}
try {
Updater.sleep(0L);
}catch(Exception e) {
e.printStackTrace();
}
}
}
this is the code present in my external updater jar and I need to find the main program directory what can I do?
For example, if the main program is in any other directory except the Desktop, the update will always download it to the desktop ... I need it to change the file that executes the command to start the updater
If your external updater is in the same directory as your mail application you can use:
System.getProperty("user.dir");
This will give you the current folder. You can find more details here: https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
If this is not the case i see the following options:
ask the user before updating for the installation folder
store the installation folder in property file inOS user data // update jar folder.
regards, WiPu
My app should save files to a place where, when you connect your phone/tablet to a computer, you can see them through the system file explorer.
This is the way I implemented file writing:
protected String mDir = Environment.DIRECTORY_DOCUMENTS;
protected File mPath = Environment.getExternalStoragePublicDirectory(mDir);
protected void writeLogFile(String filename) {
File f = new File(mPath, filename + ".txt");
f.getParentFile().mkdirs();
try (BufferedWriter bw = new BufferedWriter(new FileWriter(f, false))) {
// Details omitted.
} catch (Exception e) {
e.printStackTrace();
return;
}
makeText("Wrote " + f.getAbsolutePath());
}
This is what I see when I connect my Sony Xperia Z4 tablet to Windows (notice missing documents folder):
This is the directory to which the file is written (using above implementation):
What is wrong with my implementation?
What is wrong with my implementation?
MediaStore has not discovered your newly-created files yet. What you see in Windows — and in many on-device "gallery" apps — is based on what MediaStore has indexed.
Use MediaScannerConnection and its scanFile() method to tell MediaStore about your file, once you have written out your data to disk:
public void scanFile(Context ctxt, File f, String mimeType) {
MediaScannerConnection
.scanFile(ctxt, new String[] {f.getAbsolutePath()},
new String[] {mimeType}, null);
}
or, in Kotlin:
fun scanFile(ctxt: Context, f: File, mimeType: String) {
MediaScannerConnection.scanFile(ctxt, arrayOf(f.getAbsolutePath()), arrayOf(mimeType), null)
}
Sorry for my English, but I want to write in this file because in my opinion is the best.
Now my problem:
I want to create a folder in Internal storage to share with 2 application.
In my app, I downloaded an Apk from my server and I run it.
Before I used external storage and everything worked.
Now I want to use the internal storage for users that don't have an external storage.
I use this:
String folderPath = getFilesDir() + "Dir"
but when i try to run the Apk, it doesn't work, and I can't find this folder on my phone.
Thank you..
From this post :
Correct way:
Create a File for your desired directory (e.g., File path=new
File(getFilesDir(),"myfolder");)
Call mkdirs() on that File to create the directory if it does not exist
Create a File for the output file (e.g., File mypath=new File(path,"myfile.txt");)
Use standard Java I/O to write to that File (e.g., using new BufferedWriter(new FileWriter(mypath)))
Enjoy.
Also to create public file I use :
/**
* Context.MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application.
* Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
*/
public static void createInternalFile(Context theContext, String theFileName, byte[] theData, int theMode)
{
FileOutputStream fos = null;
try {
fos = theContext.openFileOutput(theFileName, theMode);
fos.write(theData);
fos.close();
} catch (FileNotFoundException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
}
}
Just set theMode to MODE_WORLD_WRITEABLE or MODE_WORLD_READABLE (note they are deprecated from api lvl 17).
You can also use theContext.getDir(); but note what doc says :
Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
Best wishes.
You can create a public into a existing system public folder, there is some public folder accessible from internal storage :
public static String DIRECTORY_MUSIC = "Music";
public static String DIRECTORY_PODCASTS = "Podcasts";
public static String DIRECTORY_RINGTONES = "Ringtones";
public static String DIRECTORY_ALARMS = "Alarms";
public static String DIRECTORY_NOTIFICATIONS = "Notifications";
public static String DIRECTORY_PICTURES = "Pictures";
public static String DIRECTORY_MOVIES = "Movies";
public static String DIRECTORY_DOWNLOADS = "Download";
public static String DIRECTORY_DCIM = "DCIM";
public static String DIRECTORY_DOCUMENTS = "Documents";
To create your folder, use this code :
File myDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MyPublicFolder");
myDirectory.mkdir();
With this example, a public will be created in Documents and can be visible in any file's explorer app for Android.
try the below
File mydir = context.getDir("Newfolder", Context.MODE_PRIVATE); //Creating an internal dir;
if(!mydir.exists)
{
mydir.mkdirs();
}
This is what i have used and is working fine for me:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, fileName);
File parent=file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
This will create a new directory if not already present or use the existing if already present.