LibGdx not getting files from within a directory - java

In my assets folder, I have a directory called "maps" which contains a list of images I want to load.
When running:
Gdx.files.internal("maps").exists();
This returns true
and:
Gdx.files.internal("maps/Africa.png").exists();
also returns true
However, trying to list these files seems to be unfeasible:
Gdx.files.internal("maps").list().length;
returns a value of 0 for the number of files in that directory
Moreover:
Gdx.files.internal("maps").isDirectory();
returns false.
This is very puzzling for what could have seemed to been a very straightforward way of getting files from a directory.
Does anyone have any ideas to circumvent this?

Since desktop builds cannot use the list() method on internal directories, I created this script to write the file names to a text file. It uses Apache commons.io (you can put compile "commons-io:commons-io:2.4+" into your build.gradle to include it in your desktop module):
//directories within assets that you want a catalog of
static final String[] directories = {
"completeMaps",
"typeAMaps",
"typeBMaps",
"sfx",
"music"
};
public static void main (String[] args){
String workingDir = System.getProperty("user.dir");
for (String dir : directories){
File directory = new File(workingDir + "/" + dir);
File outputFile = new File(directory, "catalog.txt");
FileUtils.deleteQuietly(outputFile); //delete previous catalog
File[] files = directory.listFiles();
try {
for (int i = 0; i < files.length; i++) {
FileUtils.write(outputFile, files[i].getName() + (i == files.length - 1 ? "" : "\n"), true);
}
} catch (IOException e){
Util.logError(e);
}
}
}
Then to get a file list in a directory:
private FileHandle[] readDirectoryCatalogue (String directory){
String[] fileNames = Gdx.files.internal(directory + "/catalog.txt").readString().split("\n");
FileHandle[] files = new FileHandle[fileNames.length];
for (int i = 0; i < fileNames.length; i++) {
files[i] = Gdx.files.internal(directory + "/" + fileNames[i].replaceAll("\\s+",""));
}
return files;
}

Related

How to find the empty sub_folder and delete the empty sub_folder using android?

Has i am create sample application using android using File concepts,
Following steps are :
--- 1. I give the parent folder name "default"
--- 2. To find the parent folder to sub folder.
--- 3. List the sub folder file.
--- 4. Delete the Empty the sub folder
i will completed three steps,In the problem is how to find the sub folder are Empty given me one solution ?
sample code :
File filefirst = new File("/storage/sdcard0/Parentfoldername/");
String[] names = filefirst.list();
for (String name : names)
{
if (new File("/storage/sdcard0/Parentfoldername/" + name).isDirectory()) {
File directory = new File("/storage/sdcard0/Parentfoldername/" + name);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile())
{
if (directory.isDirectory())
{
String[] children = directory.list();
for (int i = 0; i < children.length; i++)
{
new File(directory, children[i]).delete();
}
}
}
}
}
}
This code like delete the sub_folder inside the file ,that sub_folder are deleted not folder is file but Empty sub_folder is not delete.
public class Utils {
/**
* Empty and delete a folder (and subfolders).
* #param folder
* folder to empty
*/
public static void rmdir(final File folder) {
// check if folder file is a real folder
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) {
rmdir(tmpF);
}
tmpF.delete();
}
}
if (!folder.delete()) {
System.out.println("can't delete folder : " + folder);
}
}
}
}

How can i delete the __MACOSX folder in android?

My app need to download some ZIP files to work. Once the file has been unzipped, it also reveal the __MACOSX folder, because the original file has been zipped with mac. I know that I can zip the file using the terminal to avoid that folder, but because I have lot of files, for me is better to delete this folder once the file has been unzipped.
I have tried this but it doesn't work:
private static final File MAC_FOLDER = new File(Environment.getExternalStorageDirectory().getPath() + "/folder/folder/__MACOSX");
File fileMac = MAC_FOLDER;
if(MAC_FOLDER.exists()){
fileMac.delete();
}
Any suggestions?
Thanks
It doesn't work even if try to delete the folder and hi content
File fileMac = MAC_FOLDER;
if(MAC_FOLDER.exists()){
if (fileMac.isDirectory()) {
String[] children = fileMac.list();
for (int i = 0; i < children.length; i++) {
new File(fileMac, children[i]).delete();
}
}
}
I have solved the problem using this method
public void deleteMacosxDirectory(final File MAC_FOLDER) {
// check if folder file is a real folder
if (MAC_FOLDER.isDirectory()) {
File[] list = MAC_FOLDER.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) {
deleteMacosxDirectory(tmpF);
}
tmpF.delete();
}
}
if (!MAC_FOLDER.delete()) {
System.out.println("can't delete folder : " + MAC_FOLDER);
}
}
}
File fileMac = MAC_FOLDER;
if(fileMac.exists()){
deleteMacosxDirectory(fileMac);
}

Use Java to find a File within a directory using only a Name

I'm trying to write this script that takes an Excel sheet, gets all the names of files from the cells, and moves each of those files to a specific folder. I've already got most of the code done, I just need to be able to search for each file in the source directory using just its title. Another problem is that I'm searching for multiple file types (.txt, .repos, .xlsx, .xls, .pdf, and some files don't have extensions), I only can search by the file name without the extension.
In my findAndMoveFiles method, I've got an ArrayList of each File and a Guava Multimap of XSSFCells to Strings (a cell is one cell from the Excel file and a String is the name of the folder it needs to go into, one to many relationship) as parameters. What I've got right now for the method is this.
public static void findAndMoveFiles(List<File> files, Multimap<XSSFCell, String> innerCells) {
// For each file, get its values (folders), and put that file in each of those folders
for (XSSFCell cell : innerCells.keySet()) {
// find the file in the master directory
//Finder f = new Finder();
//if (f.canBeFound(FOLDER, cell.getStringCellValue())) {
File file = find(FOLDER, cell.getStringCellValue());
//System.out.println(file.getAbsolutePath());
//List<String> values = new ArrayList(innerCells.get(cell));
/*for (String folder : values) {
File copy = file;
if (copy != null) {
System.out.println(folder);
System.out.println(copy.getAbsolutePath());
if (copy.renameTo(new File("C:\\strobell\\" + folder + "\\" + copy.getAbsolutePath()))) {
System.out.println(copy.getName() + " has been moved successfully.");
} else {
System.out.println(copy.getName() + " has failed to move.");
}
}
}*/
//}
}
}
public static File find(File dir, String fileName) {
String files = "";
File[] listOfFiles = dir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getAbsolutePath();
if (files.equals(fileName)) {
return listOfFiles[i];
}
}
}
return null;
}
I commented out parts because it wasn't working. I was getting NullPointerExceptions because some files were being returned as null. I know that it's returning null, but each file should be found.
If there are any 3rd party libraries that can do this, that would be amazing, I've been racking my brain on how to do this properly.
Instead of
File[] listOfFiles = dir.listFiles();
use
File[] listOfFiles = dir.list(new FileNameFilter() {
public boolean accept(File dir, String name) {
if( /* code to check if file name is ok */ ) {
return true;
}
return false;
}
}););
Then you can code your logic on the file names in the condition.

How to create multiple directories given the folder names

I have a list of files, the names of these files are are made of a classgroup and an id (eg. science_000000001.java)
i am able to get the names of all the files and split them so i am putting the classgroups into one array and the ids in another.. i have it so that the arrays cant have two of the same values.
This is the problem, i want to create a directory with these classgroups and ids, an example:
science_000000001.java would be in science/000000001/science_000000001.java
science_000000002.java would be in science/000000002/science_000000002.java
maths_000000001.java would be in maths/000000001/maths_000000001.java
but i cannot think of a way to loop through the arrays correctly to create the appropriate directories?
Also i am able to create the folders myself, its just getting the correct directories is the problem, does anyone have any ideas?
Given:
String filename = "science_000000001.java";
Then
File fullPathFile = new File(filename.replaceAll("(\\w+)_(\\d+).*", "$1/$2/$0"));
gives you the full path of the file, in this case science/000000001/science_000000001.java
If you want to create the directory, use this:
fullPathFile.getParentFile().mkdirs();
The above answer is really good for creating new files with that naming convention. If you wanted to sort existing files into their relative classgroups and Ids you could use the following code:
public static void main(String[] args) {
String dirPath = "D:\\temp\\";
File dir = new File(dirPath);
// Get Directory Listing
File[] fileList = dir.listFiles();
// Process each file
for(int i=0; i < fileList.length; i++)
{
if(fileList[i].isFile()) {
String fileName = fileList[i].getName();
// Split at the file extension and the classgroup
String[] fileParts = fileName.split("[_\\.]");
System.out.println("One: " + fileParts[0] + ", Two: " + fileParts[1]);
// Check directory exists
File newDir = new File(dirPath + fileParts[0] + "\\" + fileParts[1]);
if(!newDir.exists()) {
// Create directory
if(newDir.mkdirs()) {
System.out.println("Directory Created");
}
}
// Move file into directory
if(fileList[i].renameTo(new File(dirPath + fileParts[0] + "\\" + fileParts[1] + "\\" + fileName))) {
System.out.println("File Moved");
}
}
}
}
Hope that helps.

how to get name of all file in a directory and sub-directory in java

I have a directory which consist of some different sub directory which every one have several files. how can i get name of all file?
If you want to use a library, try the listFiles method from apache commons io FileUtils, which will recurse into directories for you.
Here's an example of how you could call it to find all files named *.dat and *.txt in any directory anywhere under the specified starting directory:
Collection<File> files = FileUtils.listFiles(new File("my/dir/path"), {"dat", "txt"}, true);
public static void walkin(File dir) {
String pattern = "file pattern"; //for example ".java"
File listFile[] = dir.listFiles();
if(listFile != null) {
for(int i=0; i<listFile.length; i++) {
if(listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if(listFile[i].getName().endsWith(pattern))
{
System.out.println(listFile[i].getPath());
}
}
}
}
}
Recurse through the directory structure, gathering the names of all the files that are not sub-directories.
You are looking for File.list() take a closer look into the javadoc for more details.
To list a directory using Java do something similar to this
File dir = new File(fname);
String[] list = dir.list();
if(list == null){
System.out.println("Specified directory does not exist or is not a directory.");
System.exit(0);
}else{
//list the directory content
for(int i = 0; i < chld.length; i++){
String fileName = list[i];
System.out.println(fileName);
}
Most of this code comes from here, http://www.roseindia.net/java/beginners/DirectoryListing.shtml
This programme will display the whole structure with nested files and nested sub directories with file system.
import java.io.File;
public class DirectoryStructure
{
static void RecursivePrint(File[] arr, int index, int level)
{
// terminate condition
if (index == arr.length) {
return;
}
// tabs for internal levels
for (int i = 0; i < level; i++) {
System.out.print("\t");
}
// for files
if (arr[index].isFile()) {
System.out.println(arr[index].getName());
}
// for sub-directories
else if (arr[index].isDirectory())
{
System.out.println("[" + arr[index].getName() + "]");
// recursion for sub-directories
RecursivePrint(arr[index].listFiles(), 0, level + 1);
}
// recursion for main directory
RecursivePrint(arr, ++index, level);
}
// Driver Method
public static void main(String[] args)
{
// Provide full path for directory(change accordingly)
String maindirpath = "E:\\dms\\Notes";
// File object
File maindir = new File(maindirpath);
if (maindir.exists() && maindir.isDirectory())
{
// array for files and sub-directories
// of directory pointed by maindir
File arr[] = maindir.listFiles();
System.out.println("**********************************************");
System.out.println("Files from main directory : " + maindir);
System.out.println("**********************************************");
// Calling recursive method
RecursivePrint(arr, 0, 0);
}
}
}
Using Apache Commons
String filePath = "/apps/fraud";
String[] acceptedExtension = {"ctl","otl","dat","csv","xls"};
String[] acceptedFolders = {"suresh","dir","kernel"};
Collection fileList = FileUtils.listFiles(
new File(filePath),
new SuffixFileFilter(acceptedExtension) ,
new NameFileFilter(acceptedFolders)
);

Categories