I have some files in the assets folder of my project, and I want to list them, so I put this in my code:
File dir = new File("com.packagename/assets/fonts");
File[] fileList = dir.listFiles();
Which path should I put to make it work?
I want it so users could install new fonts (I don`t know how to do this yet) so I need to list all the fonts in the folder, including post-installed fonts. If there is any other solutions, please share.
Assets and resources are accessible using file:///android_asset and file:///android_res.
But in this case you will want to do something like this :
Resources res = getResources()
AssetManager am = res.getAssets();
String fileList[] = am.list(dirFrom);
if (fileList != null) {
for ( int i = 0;i<fileList.length;i++) {
Log.d("",fileList[i]);
}
}
Related
I want to get a random image from a specific folder in Java. The code does already work inside the Eclipse IDE, but not in my runnable JAR. Since images inside the JAR file are not files, the code below results in a NullPointerException, but I'm not sure how to "translate" the code so that it will work in a runnable JAR.
final File dir = new File("images/");
File[] files = dir.listFiles();
Random rand = new Random();
File file = files[rand.nextInt(files.length)];
If the given path is invalid then listFiles() method reutrns null value. So you have to handle it if the path is invalid. Check below code:
final File dir = new File("images/");
File[] files = dir.listFiles();
Random rand = new Random();
File file = null;
if (files != null) {
file = files[rand.nextInt(files.length)];
}
If the jar is to contain the images then (assuming a maven or gradle project) they should be in the resources directory (or a subdirectory thereof). These images are then indeed no 'Files' but 'Resources' and should be loaded using getClass().getResource(String name) or getClass.getResourceAsStream(String name).
You could create a text file listing the resource paths of the images. This would allow you to simply read all lines from that file and access the resource via Class.getResource.
You could even create such a list automatically. The following works for my project type in eclipse; some minor adjustments may be needed for your IDE.
private static void writeResourceCatalog(Path resourcePath, Path targetFile) throws IOException {
URI uri = resourcePath.toUri();
try (BufferedWriter writer = Files.newBufferedWriter(targetFile, StandardCharsets.UTF_8)) {
Files.list(resourcePath.resolve("images")).filter(Files::isRegularFile).forEach(p -> {
try {
writer.append('/').append(uri.relativize(p.toUri()).toString()).append('\n');
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
writeResourceCatalog(Paths.get("src", "main", "resources"), Paths.get("src", "main", "resources", "catalog.txt"));
After building the jar with the new file included you could simply list all the files as
List<URL> urls = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(WriteTest.class.getResourceAsStream("/catalog.txt"), StandardCharsets.UTF_8))) {
String s;
while ((s = reader.readLine()) != null) {
urls.add(SomeType.class.getResource(s));
}
}
It seem like a path Problem, maybe will work if tried absolute path for image directory or set maon directory for java configuration
I am allowing user to choose folder before downloading files.
This is what is did to give user an option to select folder.
private void pathlist(String basepath) {
File folderlist = new File(basepath);
File[] folders = folderlist.listFiles();
Log.e("Base", basepath);
for (File folder : folders) {
if (folder.isDirectory()) {
folist.add(folder.getName());
}
}
foladap = new Foladap(DownloadFolderOptions.this, folist);
listView.setAdapter(foladap);
}
where basepath = Environment.getExternalStorageDirectory().getAbsolutePath();
using above I get list of folders at Internal Memory.
But problem is when I select any folder like Movies, the final selected is
/storage/emulated/0/Movies
and System create a new folder at selected path instead of folder shown in list.
How to handle this.?
pls guide.
if I select Movies folder using Asus File Manager, the path shows as Root/Sdcard/Movies. what is this path and how it is different then what I selected as got after selection.
In the assets folder I have another folder called songs with .txt files. I've been trying to put all .txt files in a File[ ] but I get a NullPointer on folder.listFiles().
Here's the code :
File folder = new File("assets/songs");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
String content = FileUtils.readFileToString(file);
this.list.add(content);
System.out.println(content);
}
}
return this.list;
Assets are not files on the device. They are files on the development machine. They are entries inside the APK file on the device.
Use AssetManager to work with assets, including its list() method.
As sir #CommonsWare mentioned, you can use AssetManager like this:
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
Note that this file is String array. So don't forget to initialize new file for each element of the array before iterating over it.
I want to list all files in folder which is in assets. But new File("/android_asset/instagram").exists() always returns false.
File instagram = new File("/android_asset/instagram")
for (File lookUpFile : instagram.listFiles()) {
String filterName = FileUtils.removeExtension(lookUpFile.getName());
filterName = Strings.capitalizeAndCopy(filterName);
GPUImageLookupFilter lookupFilter = new GPUImageLookupFilter();
lookupFilter.setBitmap(BitmapFactory.decodeFile(lookUpFile.getAbsolutePath()));
filters.addFilter(filterName, lookupFilter);
}
Try to access the file using asset manager. Try to get the list of files and make sure its working.
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
I'm making a media player. I want to get all videos present in the sd card.
If the video is directly available in top directory of sd card, it is simple. But what about a video file exists in nested directory structure like
directory->directory->directory->file.mp4.
How can I search for a file in a nested directory structure?
You can create a list which can store the location of all the video files present on sd card. Run a loop which will visit every folder and update this array if given file format (in your case video files or .mp4) and add it to array. You can store this list onto persistent storage so as you can read it the next time your application is launched.
Here is sample code which can help you list all files in sdcard
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
fileList.add(listFile[i]);
getfile(listFile[i]);
} else {
if (listFile[i].getName().endsWith(".png")
|| listFile[i].getName().endsWith(".jpg")
|| listFile[i].getName().endsWith(".jpeg")
|| listFile[i].getName().endsWith(".gif")) {
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}
With Apache FileUtils:
import org.apache.commons.io.FileUtils;
String path = ...;
String[] extensions = {"mp4", "mov", ...};
Collection<File> allMovies = FileUtils.listFiles(new File(path), extensions, true);
am posting this, maybe it would help some one in need.
as #Jaqen H'ghar said ... i just simplify the code to add the list of the extensions u want to show.
File filePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
List<String> fileList = new ArrayList<>();
String[] extensions = {"apk","mp3","mp4","or what ever extension u want"};
Collection<File> allMovies = FileUtils.listFiles(new File(String.valueOf(filePath)), extensions, true);
for (File file: allMovies) {
fileList.add(file.getName());
}