I have the following dir tree
C:\folder1\folder2\SPECIALFolders1\folder3\file1.img
C:\folder1\folder2\SPECIALFolders2\folder3\file2.img
C:\folder1\folder2\SPECIALFolders3\folder3\file3.img
C:\folder1\folder2\SPECIALFolders4\folder3\file4.img
C:\folder1\folder2\SPECIALFolders5\folder3\file5.img
I want to get to folder2, list all dirs in it (SpecialFolders) then retrieve the paths of those folders while adding (folder3) to their path
The reason I'm doing this is I want later to pass this path (paths) to a method to retrieve last modified files in folder3. I know there are way easier ways to do it but this is a very particular case.
I'm also trying to retrieve those folders within a specific time range so I used a while loop for that
Date first = dateFormat.parse("2015-6-4");
Calendar ystr = Calendar.getInstance();
ystr.setTime(first);
Date d = dateFormat.parse("2015-6-1");
Calendar last = Calendar.getInstance();
last.setTime(d);
while(last.before(ystr))
{
//fullPath here = "C:\folder1\folder2\"
File dir = (new File(fullPath));
File[] files = dir.listFiles();
for (File file : files)
{
//Retrieve Directories only (skip files)
if (file.isDirectory())
{
fullPath = file.getPath();
//last.add(Calendar.DATE, 1);
System.out.println("Loop " + fullPath);
}
}
}
fullPath += "\\folder3\\";
return fullPath;
The problem with my code is that it only returns one path (that's the last one in the loop) --which make sense but I want to return all of the paths like this
C:\folder1\folder2\SPECIALFolders1\folder3\
C:\folder1\folder2\SPECIALFolders2\folder3\
C:\folder1\folder2\SPECIALFolders3\folder3\
C:\folder1\folder2\SPECIALFolders4\folder3\
C:\folder1\folder2\SPECIALFolders5\folder3\
I appreciate your input in advance
Instead of fullPath String, use for example ArrayList<String> to store all paths. Than instead of:
fullPath = file.getPath();
use:
yourArrayList.add(file.getPath());
Your method will return an ArrayList with all paths, and you will need to code a method to retrive all paths from it.
Related
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.
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
}
I am working on a program that must print the names of each file and subfolder in a given directory.
So far I have the following (this is just the working code):
File directory = new File( [the path] );
File[] contents = directory.listFiles();
for ( File f : contents )
{
String currentFile = f.getAbsolutePath();
System.out.println( currentFile );
}
This needs to be displayed to the user, who doesn't need to see the full path. How can I get the output to only be the file names?
This should help you
File directory = new File("\\your_path");
File[] contents = directory.listFiles();
for (File f : contents) {
System.out.println(f.getName());
}
I suppose that sometimes you might not know the path base (for whatever reason), so there is a way to split the String. You just cut the part before the slash (/) and take all that's left. As you split it, there might be (and probably is) multiple slashes so you just take the last part
String currentFile;
String[] parts;
for ( File f : contents) {
currentFile = f.getAbsolutePath();
parts = currentFile.split("/");
if (!parts.equals(currentFile)) {
currentFile = parts[parts.length-1];
}
System.out.println(currentFile);
}
Example:
"file:///C:/Users/folder/Desktop/a.html" goes to be "a.html"
The file name is being printed as a simple String, meaning that it can be edited. All you have to do is use Str.replace on your path.
This code currentFile = currentFile.replace("[the path]", ""); would replace your file path with a blank, effectively erasing it.
Some code inserted correctly, such as
for ( File f : contents)
{
currentFile = f.getAbsolutePath();
currentFile = currentFile.replace("[the path]", "");
System.out.println(currentFile);
}
will do this for each file your program finds.
Can anyone help in tuning this method? When I log the "files" - it only takes around 5 seconds. But takes more than 10 minutes before returning the "fileInfo"
// fileSystem is HDFS
// dateNow = java.util.Date
// basePath = new Path("/")
// filePattern = "*.sf"
private Map<String, Long> listFiles(final Date dateNow, final Path basePath,
final String filePattern) throws IOException {
RemoteIterator<LocatedFileStatus> files = fileSystem.listFiles(basePath, true);
_LOG.info("files=" + files);
// map containing <filename, filesize>
Map<String, Long> fileInfo = new HashMap<String, Long>();
String regex = RegexUtil.convertGlobToRegex(filePattern);
Pattern pattern = Pattern.compile(regex);
if (files != null) {
while (files.hasNext()) {
LocatedFileStatus file = files.next();
Path filePath = file.getPath();
// Get only the files with created date = current date
if (DateUtils.truncate(new Date(file.getModificationTime()),
java.util.Calendar.DAY_OF_MONTH).equals(dateNow)) {
if (pattern.matcher(filePath.getName()).matches()) {
fileInfo.put(file.getPath().getName(), file.getLen());
}
}
}
}
_LOG.info("fileInfo =" + fileInfo);
return fileInfo;
}
You Said
When I log the "files" - it only takes around 5 seconds
RemoteIterator<LocatedFileStatus> files = fileSystem.listFiles(basePath, true);
Yes. Because this part of the code only checks the File present at that path (eg.:- no.Of Files,size) Status not looking into the file what and how much data it Contains.
Now if you look into this part of code
while (files.hasNext()) {
LocatedFileStatus file = files.next();
Path filePath = file.getPath();
// Get only the files with created date = current date
if (DateUtils.truncate(new Date(file.getModificationTime()),
java.util.Calendar.DAY_OF_MONTH).equals(dateNow)) {
if (pattern.matcher(filePath.getName()).matches()) {
fileInfo.put(file.getPath().getName(), file.getLen());
}
}
}
then you analyze that it Iterate throughout the Content of all the files in List. So, Definitely It will take more time than the previous one. This files may contains a number of files with different size of Content.
So, Iterating into each file content will definitely took more time. It also depends upon the size of the files this directory Contains. The more large your file the more time would took this loop.
Use listStatus with a PathFinder. This does much of the work on the server-side, and accumulated.
I have DirectoryPath:
data/data/in.com.jotSmart/app_custom/folderName/FileName
which is stored as a String in ArrayList
Like
ArrayList<String> a;
a.add("data/data/in.com.jotSmart/app_custom/page01/Note01.png");
Now from this path I want to get page01 as a separate string and Note01 as a separate string and stored it into two string variables. I tried a lot, but I am not able to get the result. If anyone knows help me to solve this out.
f.getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
For example
File f = new File("/home/jigar/Desktop/1.txt");
System.out.println(f.getParent());// /home/jigar/Desktop
System.out.println(f.getName()); //1.txt
Update: (based on update in question)
if data/data/in.com.jotSmart/app_custom/page01/Note01.png is valid representation of file in your file system then
for(String fileNameStr: filesList){
File file = new File(fileNameStr);
String dir = file.getParent().substring(file.getParent().lastIndexOf(File.separator) + 1);//page01
String fileName = f.getName();
if(fileName.indexOf(".")!=-1){
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}
}
For folder name: file.getParentFile().getName().
For file name: file.getName().
create a file with this path...
then use these two methods to get directory name and file name.
file.getParent(); // dir name from starting till end like data/data....../page01
file.getName(); // file name like note01.png
if you need directory name as page01, you can get a substring of path u got from getparent.
How about using the .split ?
answer = str.split(delimiter);