Move inside a particular directory without knowing its name - java

I want to move inside a directory in Java but I don't know its name? Does Java provide any functionality to do so?
File srcFile = "C:/Entertainment/XXXXXXX/break.avi"
I am certain that there is only one directory inside Entertainment but I don't know its name. How can I move inside XXXXXXX directory to access any file inside it?
Any help?

Try,
File file = new File("C:/Entertainment");
File[] files = file.listFiles();

File srcDir = new File("C:/Entertainment/");
File srcFile = null;
for (File dirMember : srcDir.listFiles()) {
if (!dirMember.isDirectory()) {
continue; // we don't need regular files
}
if (dirMember.getName().equals(".")) {
continue; // we don't need this directory
}
if (dirMember.getName().equals("..")) {
continue; // we don't need the parent directory
}
// This is the one you need.
srcFile = new File(new File(srcDir, dirMember.getName()), "break.avi");
}
You could also use a FileFilter, e.g one from Commons IO
File dir = new File("C:/Entertainment/");
File[] files = dir.listFiles( DirectoryFileFilter.INSTANCE ); // returns all subdirs
srcFile = new File(files[0], "break.avi");

File srcFile = new File("C:\\Entertainment");
srcFile = new File(srcFile, srcFile.list()[0]);
srcFile = newFile(srcFile, "break.avi");
System.out.println(srcFile.getPath());

File outer= new File("C:/test");
File inner = outer.listFiles()[0];//if you are sure there is one
File[] listOfFilesInInnerMost = inner.listFiles();
System.out.println("Files: " + Arrays.asList(listOfFilesInInnerMost));
will print
Files: [C:\test\something\text (2).txt, C:\test\something\text (3).txt, C:\test\something\text.txt]

Related

How To Rename A Folder In Java

how to rename a file in java . I am trying some codes, But it can rename file and not a folder , i want to rename the folder which has like 200 or 300 files in it . Can anyone help me in this ?
The following example renames the directory “test” to “dist” in the current directory:
File sourceFile = new File("test");
File destFile = new File("dist");
if (sourceFile.renameTo(destFile)) {
System.out.println("Directory renamed successfully");
} else {
System.out.println("Failed to rename directory");
}
Search for java rename folder and you will get plenty of examples.
For example try this:
It checks if the dirPath is a directory and renames it to the given name.
File dir = new File(dirPath);
if (!dir.isDirectory()) {
System.err.println("There is no directory # given path");
} else {
System.out.println("Enter new name of directory(Only Name and Not Path).");
String newDirName = scanner.nextLine();
File newDir = new File(dir.getParent() + "\\" + newDirName);
dir.renameTo(newDir);
}
How to rename the folder in java

Problem with Array list in java (always take the last element into the array)

I have a problem with array list
public void loadFiles(String folder, List<MyFile> listFiles) {
MyFile myfile = new MyFile();
File directory = new File(folder);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isDirectory()) {
loadFiles(file.toString());
}
if (file.isFile()) {
//set name and size to myfile
myfile.setName(file.getName());
myfile.setSize(file.length());
listFiles.add(myfile);
}
}
}
On folder (Myfolder) have 3 file (TC1,TC2,TC3).
but in listFiles output (TC1,TC1,TC1)
what is going on explain me.
And How to fix this issue
thanks
You are adding the same object to the List each time you loop through the files. You need to create a new file to add, not just change the name of myFile each time:
if (file.isFile()) {
//set name and size to NEW MyFile
MyFile newFile = new MyFile();
newFile .setName(file.getName());
newFile .setSize(file.length());
listFiles.add(newFile );
}
Thanks #Raj
"create a new instance like MyFile myfile = new MyFile(); inside the for loop and then add it to the listFiles. Currently you are just adding the same object multiple times." – Raj 1 min ago
public void loadFiles(String folder, List<MyFile> listFiles) {
File directory = new File(folder);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
**MyFile myfile = new MyFile();**
if (file.isDirectory()) {
loadFiles(file.toString());
}
if (file.isFile()) {
//set name and size to myfile
myfile.setName(file.getName());
myfile.setSize(file.length());
listFiles.add(myfile);
}
}
}
It work .
Thanks All.
In your example, you want to get three different file instances in your list, but you create only one - you execute a new MyFile() only once in your code.
So you get three references to the same object. And whenever you change properties of that instance via myfile.setName(file.getName()); and myfile.setSize(file.length());, you see the change in all places where you reference this instance, so you get the same results in all three places of your list.
Instead of
myfile.setName(file.getName());
myfile.setSize(file.length());
you should do something like
myfile = new MyFile(file.getName(), file.length());
inside your loop.

Verify whether the file path contains particular String or not using java

I have one file path which is populated using File interface:-
File folder = new File("C:\\Program Files\\SmartBear\\ReadyAPI-2.2.0\\bin")
File[] listOfFiles = folder.listFiles();
File fOut = listOfFiles[0];
System.out.println(fOut)
It prints all the files inside bin folder. lets say, actions, ext, listeners
Now, I need to verify using if else statement whether the files inside the bin folder contains the particular file I am searching for?
Can we do it using java?
Here is a general example based on String.contains():
String expectedString = "PartOfFilename";
File folder = new File("/path/to/directory");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.getName().contains(expectedString)) {
//matching file found
}
}

Android files get repeated

I'm trying to list all the files in a directory.
Here is my code:
public List<String> MyFiles = new ArrayList<>();
dir = "/storage/sdcard0";
File f = new File(dir);
File[] files = f.listFiles();
for(File name: files) {
MyFiles.add(name.getName());
}
Collections.sort(MyFiles);
The problem is that nearly all the files is repeated.
For Instance I find .nomedia twice and sometimes thrice even thought there is only one file.
Edit:
I changed the code to sort the files correctly thanks to Vishwesh Jainkuniya, but still the same problem the files are repeated.
Problem-: sort function is not applicable for File[]
Solution:- create a string array and sort it.
Try this-:
First of all get the path of root dir
String path = Environment.getExternalStorageDirectory().toString();
Now append your dir name in path
path += "";
Now get the files in a array
File f = new File(path);
File file[] = f.listFiles();
String[] fileName = new String[file.length];
for (int i=0; i < file.length; i++)
{
fileName[i] = file[i].getName();
Log.d("Files", "FileName:" + file[i].getName());
}
Now sort
Arrays.sort(fileName);

How to search for files in directory that start with String

I have a directory full of text files. The naming convention of these files is {userName} + {dayOfYear}
SuperMan201
JamesBond056
JamesBond101
JamesBond093
JamesBondImposter004
SuperMan051
JamesBond057
JamesBond004
I want to search through my files for files that start with Jamesbond. How can I get the first instance of a text file that starts with Jamesbond and not get JamesBondImposter matching my search.
I have a LinkedHashSet that stores the usernames of the users that have text files in the directory. Essentially I want to get the first instance of a JamesBond text file read the file,move the file to another directory, then read subsequent files if they exist; and then move on to the next username in the LinkedList.
If you want to select files from directory take a look at https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FileFilter) and https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FilenameFilter) - just write the filter that will match what you want
Using Apache commons-io (listFiles and iterateFiles methods). Usually the code looks something like this:
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("James*");
File[] files = dir.listFiles(fileFilter);
if(files!=null && files.length > 0)
{
your desired file is files[0]
}
If you're using Java 8, you can do this:
Path dir = Paths.get(fullPathOfDirectory);
Stream<Path> jamesBondFiles = Files.list(dir).filter(path ->
path.getFileName().toString().matches("JamesBond\\d+"));
Iterator<Path> i = jamesBondFiles.iterator();
while (i.hasNext()) {
Path file = i.next();
try (BufferedReader reader = Files.newBufferedReader(file)) {
// Read and process file
}
}
If you're using Java 7, or don't want to use a Stream, you can do:
Path dir = Paths.get(fullPathOfDirectory);
final PathMatcher matcher =
dir.getFileSystem().getPathMatcher("regex:JamesBond\\d+");
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
#Override
public boolean accept(Path path) {
return matcher.matches(path.getFileName());
}
};
try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, filter)) {
Charset charset = Charset.defaultCharset();
for (Path file : ds) {
try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
// Read and process file
}
}
}

Categories

Resources