How to change names of files in String[] - java

I have such code...
File fileDir = new File("/mnt/sdcard/dd");
if(!fileDir.exists() || !fileDir.isDirectory()){
return;
}
String[] files = fileDir.list();
So, I have an array of files' names...
But I want to GET an array of "path to each file"+fileDir.list()
For example
I have - "/09.jpg"
I want - "/mnt/sdcard/dd/09.jpg"
How can I do it? Thanks

try following code,
String path = "/mnt/sdcard/dd";
File fileDir = new File( path );
if(!fileDir.exists() || !fileDir.isDirectory())
{
return;
}
String[] files = fileDir.list();
for ( int i = 0 ; i < files.length ; i++ )
{
files[i] = path + "/" + files[i];
}
Now the array files contains the updated value with path.

File fileDir = new File("/mnt/sdcard/dd");
if(!fileDir.exists() || !fileDir.isDirectory()){
return;
}
File[] files = fileDir.listFiles();
for(File f: files){
Log.i("", f.getAbsolutePath());
}

What you need is getAbsolutePath(),
File file = new File("/mnt/sdcard/dd");
Files[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
Log.e("Root Path of file:" + i, files[i].getAbsolutePath());
}

Related

How to arrange and rename files according to number?

I want to arrange files first and rename them according to their order that is specified by a number in the file name.
For example:
I have a folder that contains a bunch of different files. The file names are indicated by a number at the end of it. Let's say we have the following files in that folder:
file_1.xml // Remains unchanged
file_2.xml // Remains unchanged
file_4.xml // Should be renamed to "file_3.xml"
file_9.xml // Should be renamed to "file_4.xml"
file_12.xml // Should be renamed to "file_5.xml"
How do I do that? I want to create a reliable clean method that renames files in order.
So far:
private void updateFilesName() {
for (int i = 1; i <= filesAmount; i++) {
File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml");
File file2 = new File(getFilesDir().getParent() + "/file_" + String.valueOf(i + 1) + ".xml");
if (!file1.exists() && file2.exists()) {
file2.renameTo(file1);
}
}
}
But that only works if the difference between 2 file positions was 1. (like between file_2 and file_4) This method won't work for file_9 and file_12.
private void updateFilesName() {
int j;
for (int i = 1; i <= filesAmount; i++) {
File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml");
if (!file1.exists()) {
j = i+1;
while (!(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).exists()) {
j++;
}
(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).renameTo(file1);
}
}
}
// Iterate all files under the directory and check the file name
File folder = new File("urdirectory");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
if (!listOfFiles[i].getName().equals("file_" + (i+1) + ".xml")) {
File tempFile1 = listOfFiles[i];
File tempFile2 = new File("urdirectory" + "/file_" + String.valueOf(i + 1) + ".xml");
tempFile.renameTo(tempFile2);
}
}

How to speed up File Storage Access?

I am trying to get a list of all Folders that contain MP3 Files on the user's Internal Storage.
Here is the recursive function that I am calling for this purpose -
public void listAllMusicFiles(String pathToDirectory) {
String lastFolderPath = "";
int mp3Count = 0;
File f = new File(pathToDirectory);
File[] files = f.listFiles();
for (File inFile : files) {
if (inFile.isDirectory()) {
//reset last folder path
lastFolderPath = "";
Log.d("Directory ", inFile.getPath());
listAllMusicFiles(inFile.getPath());
} else {
if (inFile.getAbsolutePath().endsWith(".mp3") || inFile.getAbsolutePath().endsWith(".MP3")) {
mp3Count++;
Log.wtf("MP3 Count", mp3Count + " ");
//add each folder only once
String folderName = inFile.getParentFile().getName();
String folderPath = inFile.getParentFile().getPath();
Log.e("FOUND in", folderPath);
//create a new Folder object
Folder currentFolder = new Folder(folderName, folderPath, mp3Count + "");
if (!lastFolderPath.equals(folderPath)) {
Log.d("NEW", folderPath);
lastFolderPath = folderPath;
folderArrayList.add(currentFolder);
} else {
Log.d("OLD", folderPath);
//find a Folder object in folderArrayList where the object's path matches current folderPath
for (Folder folder : folderArrayList) {
String currentPath = folder.getFolder_Path();
if (currentPath.equals(folderPath)) {
//found a match
//update count
folder.setFolder_Song_Count(mp3Count + "");
}
}
}
}
}
}
}
When I run this code on my device, I am able to list the required folders in a RecyclerView, but with a delay of about 6-7 seconds.
I have already moved this task into an AsyncTask, so that my UIThread does not hang because of this intensive operation.
But I am totally at a loss when it comes to improving File System Performance. Kindly help. Thanks !
Instead of storing currentFolder in an ArrayList and in the next step iterating through complete list to find that folder and updating the value, you can simply use HashMap like this
HashMap<String, Folder> folders = new HashMap<>();
public void listAllMusicFiles(String pathToDirectory) {
int mp3Count = 0;
File f = new File(pathToDirectory);
File[] files = f.listFiles();
Folder folder;
String folderName, folderPath;
for (File inFile : files) {
if (inFile.isDirectory()) {
//reset last folder path
Log.d("Directory ", inFile.getPath());
listAllMusicFiles(inFile.getPath());
} else {
if (inFile.getAbsolutePath().endsWith(".mp3") || inFile.getAbsolutePath().endsWith(".MP3")) {
mp3Count++;
Log.wtf("MP3 Count", mp3Count + " ");
//add each folder only once
folderName = inFile.getParentFile().getName();
folderPath = inFile.getParentFile().getPath();
Log.e("FOUND in", folderPath);
if (folders.containsKey(folderPath)) {
folder = folders.get(folderPath);
folder.setFolder_Song_Count(mp3Count + "");
folders.put(folderPath, folder);
} else {
folder = new Folder(folderName, folderPath, mp3Count + "");
folders.put(folderPath, folder);
}
}
}
}
}

Always the last element's informations are shown in the List (Java)

I have some Lists consist of some Apk files' informations:
static ContentAndDAO contentAndDao = new ContentAndDAO();
public static void main(String[] args)
{
int manifestNum;
long contentId = 111111;
long devFileId = 222222;
List<DevFile> fileList;
List<DevSupport> supports = null;
List<ContentDev> contentList = new ArrayList<ContentDev>();
ContentDevDAO contentDevDao = new ContentDevDAO();
DevFileDAO devFileDao = new DevFileDAO();
ManifestMethods manifestMethods = new ManifestMethods();
DevFile apkFile = null;
try
{
manifestNum = 1;
File dir = new File("C:\\Users\\lenovo 01\\Desktop\\basari\\buulkcontent\\klasorlenen");
String[] extensions = new String[] {"apk"};
List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
Collections.sort(files);
for(File file : files)
{
apkFile = new DevFile();
fileList = new ArrayList<DevFile>();
if(file.getName().contains(".apk"))
{
FileInputStream fis = new FileInputStream(new File(file.getAbsolutePath()));
String apkMd5 = DigestUtils.md5Hex(fis);
fis.close();
System.out.println(file);
System.out.println(file.length());
System.out.println(apkMd5.toUpperCase());
System.out.println(contentId);
apkFile.setByteSize(file.length());
apkFile.setUrl("/file/getContent/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + "/apk");
apkFile.setThumbnailUrl("/file/getContent/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + "/apk");
apkFile.setDeleteUrl("/file/deleteContent/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + "/apk");
apkFile.setFileHash(apkMd5.toUpperCase());
apkFile.setFilePath("content/" + contentDevDao.createId(contentId) + "/" + apkMd5.toUpperCase() + ".apk");
apkFile.setFileName(manifestMethods.getApplicationName(manifestNum).replaceAll(" ", "-") + ".apk");
apkFile.setName(manifestMethods.getApplicationName(manifestNum).replaceAll(" ", "-"));
apkFile.setPackageVersion(manifestMethods.getVersionName(manifestNum));
apkFile.setPackageName(manifestMethods.getPackageName(manifestNum));
apkFile.setPackageVersionCode(manifestMethods.getVersionCode(manifestNum));
apkFile.setSdkVersion(manifestMethods.getSdkVersion(manifestNum));
contentId++;
devFileId++;
manifestNum++;
}
}
for(int y = 1; y <= 53; y++)
{
manifestNum = 1;
fileList = new ArrayList<DevFile>();
DevFile file = new DevFile();
ContentDev content = new ContentDev();
/* some DevFile file addings */
fileList.add(file);
content.setDevFiles(fileList);
contentList.add(content);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
When I print the information one by one to the console, its showing just as I want. But in the List, its always showing only the last added apk file's package name, byte size, hash number etc. Of course I don't want that. What is wrong?
Note: Please don't mind the lack of legibility and modularity of code. I'm new to the object oriented structure.
You are creating a new list in each iteration of your loop :
for(int y = 1; y <= 53; y++)
{
fileList = new ArrayList<DevFile>();
DevFile file = new DevFile();
ContentDev content = new ContentDev();
/* some DevFile file addings */
fileList.add(file);
...
This means only the last file will be in that list at the end.
Change it to :
fileList = new ArrayList<DevFile>();
for(int y = 1; y <= 53; y++)
{
DevFile file = new DevFile();
ContentDev content = new ContentDev();
/* some DevFile file addings */
fileList.add(file);
...
In addition, I see that you create instances of DevFile in another loop, but never do anything with them. Shouldn't they be added to the List?

Deleting Multiple Files Java (Android)

I'm new to programming Android, and I want to delete Files on the sd-card. This is my current (working) code...
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "ApplifierVideoCache");
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
Now I want to delete multiple files, but dont want to mention each file with that big block. Am I able to combine all files in one variable? Thanks ;)
Make a recursive method:
/*
* NOTE: coded so as to work around File's misbehaviour with regards to .delete(),
* which does not throw an exception if it fails -- or why you should use Java 7's Files
*/
public void doDelete(final File base)
throws IOException
{
if (base.isDirectory()) {
for (final File entry: base.listFiles())
doDelete(entry);
return;
}
if (!file.delete())
throw new IOException ("Failed to delete " + file + '!');
}
Another possibility would be using the Apache commons-io library and calling
if (file.isDirectory())
FileUtils.deleteDirectory(File directory);
else {
if(!file.delete())
throw new IOException("Failed to delete " + file);
}
You should make a method out of this chunk of code, pass file name and call it whenever you like:
public void DeleteFile(String fileName) {
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), fileName);
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
}
File dir = new File(android.os.Environment.getExternalStorageDirectory(),"ApplifierVideoCache");
Then call
deletedir(dir);
public void deletedir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
listFile[i].delete();
}
}
}
or if your folder as sub folders then
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++)
{
if (listFile[i].isDirectory())
{
walkdir(listFile[i]);
} else
{
listFile[i].delete();
}
}
}
For kotlin
Create a array of path list
val paths: MutableList<String> = ArrayList()
paths.add("Yor path")
paths.add("Yor path")
.
.
delete file for each path
try{
paths.forEach{
val file = File(it)
if(file.exists(){
file.delete()
}
}
}catch(e:IOException){
}

Readin from /data/dalvik-cache JavaNullPointer

I'm trying to list all files in /data/dalvik-cache folder but i keep getting NullPointerException
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
File folder = new File(dir);
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName() );
}
}
The array dalvikPath contains /data/dalvik-cache
I request su before trying to list and I think i have all the permissions in my manifest.
I think you need to check directory is exist or not . then you can get list of files
File folder = new File(dir);
if(folder.exists()){
File list[] = folder.listFiles();
if(list.length>0{
for( int i=0; i< list.length; i++){
}
}
}else{
}
Ok so i've modified my code and now i don't have javanullpointer but i don't "find" an files in the folders...
List<String> dalvikFiles = new ArrayList<String>();
for (String dir : dalvikPath) {
log.append("Reading " + dir + "\n");
File folder = new File(dir);
if (folder.exists() && folder.isDirectory()){
try{
File list[] = folder.listFiles();
for( int i=0; i< list.length; i++)
{
dalvikFiles.add( list[i].getName().toString() );
log.append(list[i].getName().toString() +"\n");
}
}
catch ( Exception e) {
}
}
else {
log.append("Folder " + dir + "doesn't exist.\n");
}

Categories