Java android delete File - java

I want to delete a file (pdf file) I did this :
boolean deleted = filesList.get(pos).delete();
But when I look in my phone I see this file , but my application doesn't see this file

To delete a file from a directory, you can use this method:
public static void deleteFile(File directory, String fileName) {
if (directory.isDirectory()) {
for(File file : directory.listFiles()) {
if (file.getName().contains(fileName)) {
if (file.isFile()) {
if (file.exists()) {
file.delete();
}
}
}
}
}
}
And if you want to delete the entire directory:
public static void deleteDirectory(File directory) {
if (directory.isDirectory())
for (File child : directory.listFiles())
deleteDirectory(child);
directory.delete();
}
As mentioned by ylmzekrm1223, you should provide permissions to read and write storage in your AndroidManifest.xml, before attempting to delete a file or a directory.

Your code doesn't delete a file from the file system. It just deletes an element from the list.
Check this for more
delete file in sdcard
To delete a file from the file system, first you need to provide Permission to read and write local storage in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Then, in your code,
String path = "/mnt/sdcard/test.pdf";
File mFile = new File(path);
mFile.delete();

Related

copy Resource folders files after deployment in spring boot app

private static void copyRequiredCBAFiles(String sourceFileUrl, Path targetDirectory, String fileName, Boolean rename) throws IOException {
File source = new File(new ClassPathResource(sourceFileUrl).getFile().getAbsolutePath());
File destination = targetDirectory.toFile();
for (File file : source.listFiles()) {
if (file.isFile()) {
if (rename && (StringUtils.equalsIgnoreCase(file.getName(),"template.txt") || StringUtils.equalsIgnoreCase(file.getName(), "mapping.json"))) {
copyAndRenameFileToDirectory(file, destination, fileName);
} else {
FileUtils.copyFileToDirectory(file, destination);
}
}
}
}
i have some files and subfolders inside resouces folder, Now after deploy the code im not able to access it im getting null pointer exception. Is it possible to access those files and folders.

is it possible to read the downloaded file from chrome browser using selenium

I downloaded a text file by a click button functionality, using Selenium Java.
then the file is downloaded to a particular location in the system, for example,
C://myAppfiles.
But I can't access that downloaded folder because of some reason. But I have to read that file while downloading.
How to do it? is it possible to read that file from the browser(chrome) using selenium or any other method is available?
so I'd suggest to do the following:
wait until file download is done completely.
After that- try to list all the files in the given directory:
all files inside folder and sub-folder
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
files/folder only
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
System.out.println(f.getName());
if(f.isFile()){
System.out.println(f.getName());
}
}
}
That will help You to understand if there any files at all (in the given directory).
Dont forget to make paths platform independent (to the folder/ file), like:
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"myDownloadedFile.txt");
Also, You might want to check whether file actually exists via Path methods.
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws Exception {
Path filePath= Paths.get("C:\\myAppfiles\\downloaded.txt");
System.out.println("if exists: " + Files.exists(firstPath));
}
}
Additionally, path suggests You to check some other options on the file:
The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.
Path file = ...;
boolean isRegularExecutableFile = Files.isRegularFile(file) &
Files.isReadable(file) & Files.isExecutable(file);
Once You face any exception- feel free to post it here.
Hope this helps You

How to create Directory and See it on Computer

I try to create directory on Tablet and want to see it.
I create directory with this code
public void createDirectory(String sDirectoryName) {
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
File fileWithinMyDir = new File(direct, "myfile");
if(!direct.exist()) {
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
}
I see everytime Directory created, But when I search Folder in file system, I can not see it. How can I make it visible. Am I making wrong?
EDIT:
I gave all permission on manifest. And I tried this code too
File direct = new File(Environment.getExternalStorageDirectory()+"/"+sDirectoryName);
if(!direct.exists())
{
if(direct.mkdir())
{
System.out.println("Directory created");
Toast.makeText(MainActivity.this, "Directory created", Toast.LENGTH_LONG).show();
}
else
{
System.out.println("Directory not created");
Toast.makeText(MainActivity.this, "Directory not created", Toast.LENGTH_LONG).show();
}
}
But this is not working for me too.
EDIT:
For refreshing I use this code.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
working.
Note: because Android uses the MTP protocol for USB connections sometimes a file or folder just wont show because everything is cached and may need a refresh.
More info: Nexus 4 not showing files via MTP
File does not create a file if it doesn't exist. It just stores the path to it. Your if statement shows it doesn't exist.
Try this...
public void createDirectory(String sDirectoryName)
{
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), sDirectoryName);
if (!file.exists()) {
file.mkdirs();
}
}
Use below code to create directory.
public void createDirectory(String sDirectoryName) {
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
File fileWithinMyDir = new File(direct, "myfile");
if(!direct.exist()) {
direct.mkdirs();
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
}
Add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Make sure that your manifeist have the following permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And in code
File directory = new File(Environment.getExternalStorageDirectory()+DOC_FOLDER_NAME);
// create directory if not exists
if(!directory.exists())
{
if(directory.mkdirs()) //directory is created;
Log.i(" download ","App dir created");
else
Log.w(" download ","Unable to create app dir!");
}
To create a dir:
if(!direct.exist()) {
if (direct.mkdir())
Log.i(TAG, "Directory created");
else
Log.w(TAG, "Failed to create directory");
}
and don't forget permissions in your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Your print statement is confusing :
if(!direct.exist()) { // If directory does not exist
System.out.println("Directory created"); // Directory created not true
}
As just creating a File object it will not create directory the code should be:
if(!direct.exist()) { // If directory does not exist
direct.mkdir(); // Create directory
System.out.println("Directory created");
}
else {
System.out.println("Directory not created");
}
Also make sure to add android.permission.WRITE_EXTERNAL_STORAGE permission in your application.
Additionally its suggested not to use System.out.println in Android as On the emulator and most devices System.out.println gets redirected to LogCat and printed using Log.i(). This may not be true on very old or custom Android versions.
in manifest add this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and this for java file:
File myDirectory = new File(Environment.getExternalStorageDirectory(), "dirName");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
to delete it:
myDirectory.delete();
and this for File object for the parent directory:
//create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
Is the issue not on the line
File direct = getDir(sDirectoryName, Context.MODE_PRIVATE);
According to the documentation context.MODE_PRIVATE will only be visible within the app itself another program or user ID won't be able to find it.
try:
File direct = getDir(sDirectoryName, Context.MODE_WORLD_READABLE);
or
File direct = getDir(sDirectoryName, Context.MODE_WORLD_WRITEABLE);
http://developer.android.com/reference/android/content/Context.html

Reading files inside a APK

I am having an android application that is using an external jar that
has in addition to regular classes an html file.
Meaning my final apk root directory looks something like this
assests
res
AndroidManifest.xml
classes.dex
resources.arsc
helloworld.html
How can I access from my application to the last file
"helloworld.html"?
Android package hierarchy is not a like java application package.
So you can't access files like this.
I think you have to use this helloworld.html file in your application.
So put this file in /asset directory and in your activity code just get file using
getAssets().
also access file like: file:///android_asset/helloworld.html
Why not making a library project instead of a jar?
You have to replace the string "assets/SecureManifest.xml" with your file "helloworld.html"
public static InputStream getInputStreamFromApkResource(String apkFilePath, String apkResPath) throws IOException {
JarFile jarFile = new JarFile(apkFilePath);
JarEntry jarEntry = jarFile.getJarEntry(apkResPath);
return jarFile.getInputStream(jarEntry);
}
// Example usage reading the file "SecureManifest.xml" under "assets" folder:
File sdcard = Environment.getExternalStorageDirectory();
File apkFile = new File(sdcard, "file.apk");
if (apkFile.exists()) {
try {
InputStream is =getInputStreamFromApkResource(apkFile.toString(), "assets/SecureManifest.xml");
BufferedReader br = new BufferedReader( new InputStreamReader(is));
String str;
while ((str = br.readLine()) != null) {
Log.d("***", str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
The github gist can be found here

Getting multiple java files directory

I need go through a package with sub-packages that contains some java class file. Can someone teach me how to get all those java class file directories and store it in a String array?
public void getClassArray(File dir, List<String> results) {
File[] filesInDir = dir.listFiles();
for (File file : filesInDir) {
if (file.isDirectory()) {
getClassArray(file, results);
}
else if (file.getName().endsWith(".class")) {
results.add(file.getName());
}
}
}
can this work?
The other post will give you all the class file name the below code snippet will give you all the folders which have .class files within
public void getClassFolders(File file, List<String> fileNames){
for (File child : file.listFiles()) {
if(child.isDirectory()){
getClassFolders(child, fileNames);
} else if(child.getName().endsWith(".class")){
fileNames.add(file.getName());
}
}
}

Categories

Resources