A better way to convert `File[]` to `List<String>` - java

I'm trying to list all folders in sdcard via ListAdapter. But I'm getting runtime exceptions # item.add(file.getName() + "/");. Is there a better way to convert File[] to List<String>?
private List <String> item = null;
String extState = Environment.getExternalStorageState();
if (!extState.equals(Environment.MEDIA_MOUNTED)) {
....
} else {
File sd = Environment.getExternalStorageDirectory();
FileFilter filterDirectoriesOnly = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
File[] sdDirectories = sd.listFiles(filterDirectoriesOnly);
for (int i = 0; i < sdDirectories.length; i++) {
File file = sdDirectories[i];
item.add(file.getName() + "/");
}
ArrayAdapter <String> fileList = new ArrayAdapter <String>(this, R.layout.row, item);
setListAdapter(fileList);
}

You can make it a little shorter by using an enhanced for loop:
File[] sdDirectories = sd.listFiles(filterDirectoriesOnly);
for (File file : sdDirectories)
{
item.add(file.getName() + "/");
}
There's a method to get file names directly, but they won't have your trailing /, and you have to be able to filter by file name:
String[] fileNames = sd.list(fileNameFilter);
List<String> fileNamesList = Arrays.asList(fileNames);

You are getting runtime Exception bacause
private List item = null;
is never initialised..
so first initialise then add..
What ever you are doing seems just right.. except that initialization..

Initialize your list (hence the Exception). But apart from that, looks pretty much alright to me. I mean, it is atleast what I would do. The only thing I would recommend here is that you don't re-instantiate the variables File sd and FileFilter filterdirectoriesOnly within the function, because I assume you would be calling it again and again as the user clicks on a directory and then loads results for a new directory. So the two objects I mentioned are the same but being re-initialised every time you make a call. You could just move it outside.

Related

(Processing / Java) Converting a singular file function into a function that takes an array

I am trying to create a program that uploads multiple files and stores their name and BPM tag into an ArrayList ready for comparison between the files. I have found two functions to help me but I am unable to combine them to get the function that I need.
The first function takes a singular mp3 file and outputs its data into the console (using mp3agic library):
File file = new File(dataPath("") + "/Song.mp3");
Mp3File mp3file = new Mp3File(file.getPath());
if (mp3file.hasId3v2Tag()) {
ID3v2 id3v2Tag = mp3file.getId3v2Tag();
println("Track: " + id3v2Tag.getTrack());
println("Artist: " + id3v2Tag.getArtist());
println("BPM: " + id3v2Tag.getBPM());
println("Album artist: " + id3v2Tag.getAlbumArtist());
}
The second function takes a data path and outputs the directory containing the names and info of the files in the folder
void setup() {
String path = "Desktop/mp3folder";
println("Listing all filenames in a directory: ");
String[] filenames = listFileNames(path);
printArray(filenames);
println("\nListing info about all files in a directory: ");
File[] files = listFiles(path);
for (int i = 0; i < files.length; i++) {
File f = files[i];
println("Name: " + f.getName());
println("Is directory: " + f.isDirectory())
println("-----------------------");
}
}
// This function returns all the files in a directory as an array of Strings
String[] listFileNames(String dir) {
File file = new File(dir);
if (file.isDirectory()) {
String names[] = file.list();
return names;
} else {
// If it's not a directory
return null;
}
}
// This function returns all the files in a directory as an array of File objects
// This is useful if you want more info about the file
File[] listFiles(String dir) {
File file = new File(dir);
if (file.isDirectory()) {
File[] files = file.listFiles();
return files;
} else {
// If it's not a directory
return null;
}
}
The function I am trying to create combines the two. I need the Artist, Track and BPM from the first function to work with an array list of files from a directory.
Any guidance would be appreciated. Any advice on another way to go about it would also be appreciated.
One way to approach this is to use classes to encapsulate the data you want to track.
For example, here's a simplified class that contains information about artist, track, and bpm:
public class TrackInfo{
private String artist;
private String track;
int bpm;
}
I would also take a step back, break your problem down into smaller steps, and then take those pieces on one at a time. Can you create a function that takes a File argument and prints out the MP3 data of that File?
void printMp3Info(File file){
// print out data about file
}
Get that working perfectly before moving on. Try calling it with hard-coded File instances before you try to use it with an ArrayList of multiple File instances.
Then if you get stuck, you can post a MCVE along with a specific technical question. Good luck.

Scanning sub folder

I am trying to search files from sd card so i can delete multiple and duplicate files.``
private List<String> searchForFileNameContainingSubstring(String substring)
{
path = Environment.getExternalStorageDirectory().getPath() + "/";
//This is assuming you pass in the substring from input.
File file = new File(path); //Change this to the directory you want to search in.
List<String> filesContainingSubstring = new ArrayList<String>();
if (file.exists() && file.isDirectory())
{
String[] files = file.list(); //get the files in String format.
for (String fileName : files)
{
if (fileName.contains(substring))
filesContainingSubstring.add(fileName);
}
}
for (String fileName : filesContainingSubstring)
{
System.out.println(fileName); //or do other operation
}
return filesContainingSubstring; //return the list of filenames containing substring.
}
How can i scan other sub folders from sdcard/ directories
It only shows results from sdcard directories
You can use Apache Common's FileUtils.listFiles method.
You can search recursively throughout a folder by setting the third parameter as true.
Also, you can target specific file extensions by passing in the second argument a String array as seen below. If you want to target any extensions pass null.
Note: the extensions names do not include '.' it's "jpg" and not ".jpg"
String[] extensions = {"png","jpg"};
Collection images = FileUtils.listFiles(new File("dirPath"),extensions, true);
for (Object obj : images){
File file = (File) obj;
// your code logic
}

Locate a file regardless of Casing?

I'm working on a program. However, the program is that I'm on a Linux based operating system and it wants perfect case-match names for all of the files, and considering the artist has some named with Caps, some not, some have ".png" some are ".Png" and some are ".PNG", etc; this is becoming a very difficult task. There's a little over a thousand Sprites, or renaming them wouldn’t be a problem. This is for a 2D RPG Hobby project that I'm doing for learning, purposes that I've been working on for awhile now.
Anyhow, my question is if we can make the 'Compiler'(I think is the right way to word this) ignore the file ending character-casing? If I want to load the following items
1.jpg
2.Jpg
3.JPg
4.JPG
5.jpG
I would like to be able to do it in a single line.
You cannot make the compiler ignore case; this is a filesystem characteristic. Note that NTFS is case-insensitive but it is case-preserving nonetheless.
Using Java 7 you can use a DirectoryStream.Filter<Path> to collect the relevant paths; then rename if appropriate:
final DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>()
{
#Override
public boolean accept(final Path entry)
{
return Files.isRegularFile(entry)
&& entry.getFileName().toString().toLowerCase().endsWith(".jpg");
}
};
final List<Path> collected = new ArrayList<Path>();
try (
final DirectoryStream<Path> entries = Files.newDirectoryStream(dir, filter);
) {
for (final Path entry: entries)
collected.add(entry);
}
Path dst;
String targetName;
for (final Path src: collected) {
targetName = src.getFileName().toString().toLowerCase();
dst = src.resolveSibling(targetName);
if (!Files.isSameFile(src, dst))
Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
}
With Java 8 you would probably use Files.walk() and lambdas instead.
If you know the exact directory for the file, you could use File.list() to get an String[] of all files in this directory. By iterating over those and using toLowerCase() on the filenames you can find your desired file.
String filename = "1.jpg";
String targetFilename = null;
File directory = new File("/some/path");
for(String maybeTargetName : directory.list()) {
if(filename.equals(maybeTargetName.toLowerCase()) {
targetFilename = maybeTargetName;
break;
}
}
if(targetFilename != null) {
File targetFile = new File(directory, targetFilename);
}

Filtering files in a directory in Java

public class Sorter {
String dir1 = ("C:/Users/Drew/Desktop/test");
String dir2 = ("C:/Users/Drew/Desktop/");
public void SortingAlgo() throws IOException {
// Declare files for moving
File sourceDir = new File(dir1);
File destDir = new File(dir2);
//Get files, list them, grab only mp3 out of the pack, and sort
File[] listOfFiles = sourceDir.listFiles();
if(sourceDir.isDirectory()) {
for(int i = 0; i < listOfFiles.length; i++) {
//list Files
System.out.println(listOfFiles[i]);
String ext = FilenameUtils.getExtension(dir1);
System.out.println(ext);
}
}
}
}
I am trying to filter out only .mp3's in my program. I'm obviously a beginner and tried copying some things off of Google and this website. How can I set a directory (sourceDir) and move those filtered files to it's own folder?
File provides an ability to filter the file list as it's begin generated.
File[] listOfFiles = sourceDir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".mp3");
}
});
Now, this has a number of benefits, the chief among which is you don't need to post-process the list, again, or have two lists in memory at the same time.
It also provides pluggable capabilities. You could create a MP3FileFilter class for instance and re-use it.
I find the NIO.2 approach using GLOBs or custom filter the cleanest solution. Check out this example on how to use GLOB or filter example in the attached link:
Path directoryPath = Paths.get("C:", "Program Files/Java/jdk1.7.0_40/src/java/nio/file");
if (Files.isDirectory(directoryPath)) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directoryPath, "*.mp3")) {
for (Path path : stream) {
System.out.println(path);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
For more information about content listing and directory filtering visit Listing and filtering directory contents in NIO.2
if(ext.endWith(".mp3")){
//do what ever you want
}

How can move file from one directory to another

I am sorry,I modified my entire question.
I want to move some specific files(based on fileExtension) from one directory to another.
For this, I plan to write 2 functions names are ListOfFileNames and MovingFiles.
If you pass directorypath and filetype as a arguments toListOfFileNames(),it returns List<File>data.this list have entire file path.
MovingFiles() move files from source Directory to destination.
I tried MovingFiles function, in the following way.It's not working.
public void MovingFiles(String SourcePath,String directoryPath,String fileType) throws IOException
{
ExternalFileExecutions ExternalFileExecutionsObject=new ExternalFileExecutions();
List<File> fileNames=ExternalFileExecutionsObject.ListOfFileNames(SourcePath, fileType);
for (int fileIndex = 0; fileIndex < fileNames.size(); fileIndex++)
{
fileNames[fileIndex].renameTo(new File(directoryPath+"/" + fileNames[fileIndex].getName()))
}
}
I think, I need to convert List<File> to List<String>.that's why Previously I asked like that.
#tbodt replyed for my question.I failed to integrate his answer in my function.so I modified my question.
Again sorry, for modifying my entire question.
Thanks.
If you want to get a List<String> with each element the canonical path of the corresponding file, this is how:
List<String> list = new ArrayList<String>();
for (File file : finalListNames)
list.add(file.getCanonicalPath());
If that's not what you want, please clarify.
If understand you, using guava, I would write it in this way:
public static List<File> listOfFiles(){
return Lists.newArrayList(new File("source.txt"), new File("test.txt"));
}
public static List<String> listOfFileNames(){
return Lists.transform(listOfFiles(), new Function<File, String>() {
public String apply(File input) {
return input.getAbsolutePath();
}
});
}
You cant convert it. But what you can is that you can retrieve the name (what ever it is) while iterating through File list. A very handy solution would be LINQ, and select
This my answer. I used #tbodt code in my code.
public void MovingFiles(String SourcePath,String directoryPath,String fileType) throws IOException
{
ExternalFileExecutions ExternalFileExecutionsObject=new ExternalFileExecutions();
List<File> fileNames=ExternalFileExecutionsObject.ListOfFileNames(SourcePath, fileType);
List<String> list = new ArrayList<String>();
for (File file : fileNames)
list.add(file.getCanonicalPath());
for (int fileIndex = 0; fileIndex < list.size(); fileIndex++)
{
File file=new File(list.get(fileIndex));
file.renameTo(new File(directoryPath+"/",file.getName()));
}
}
you move a file from one directory to another directory with the same file name
try{
File afile =new File("C:\\folder1\\file1.txt");
if(afile.renameTo(new File("C:\\folder2\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}

Categories

Resources