filenames from catalog path in javafx - java

I want to get filnames from catalog path in Javafx 2 without extensions, but with filters (*.jpeg, *.jpg...).
Filenames should be as list of strings. But I don't know how can I do it.
If anybody know how do it, please for help.

For example manually manage such files
File f = new File("D:\\dir_name\\");
if (f.isDirectory()) {
String[] list = f.list();
for (int pos = 0; pos < list.length; pos++) {
if (list[pos].contains(".")//contains extension
&& list[pos].lastIndexOf(".") != (list[pos].length() - 1))//point is not last character
{
list[pos]=list[pos].substring(0,list[pos].lastIndexOf("."));
}
}
}

Related

How to check if a folder contains n file with a certain path

I'm developing an Android app, I have to implement a function that returns an integer.
I have a folder with different files, each file is composed from a custom path like this:
123_part_ax0.jpg
123_part_ax1.jpg
123_part_ax2.jpg
123_part_ax3.jpg
123_part1_ax0.jpg
123_part1_ax1.jpg
I need to count all file that have the same path like: 123_part_ax in this case count = 4.
* Solution that I used *
public int itemNumber(int id) {
int nItem = 0;
File dir = new File(Environment.getExternalStorageDirectory() + "/.PATH/"+id);
File[] listOfFiles = dir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if(listOfFiles[i].getName().contains("WHAT I WHAT SEARCH")){
nItem++;
}
}
return nItem;
}
For such need, you can use either File#list(FilenameFilter filter) or File#listFiles(FilenameFilter filter) to filter the content of your folder by file name then get the length of the resulting array.
For example with list(FilenameFilter):
int total = new File("/path/to/my/folder")
.list((dir, name) -> name.startsWith("123_part_ax"))
.length;

How to pass context menu parameters to Java ProcessBuilder

I am using Java ProcessBuilder to open a file with a specific program on windows.
That itself works fine, with the following code:
ProcessBuilder p = new ProcessBuilder();
p.command("C:\\Program Files (x86)\\...\\program.exe", file.getAbsolutePath());
What I want to do is to invoke the functionality of a file context menu entry from that program which looks like this:
"C:\Program Files (x86)\...\program.exe" /Enqueue "%1"
How do I have to pass those parameters to the process builder?
I already tried the following, none of which worked:
p.command("C:\\Program Files (x86)\\...\\program.exe","/Enqueue","%1",next.getAbsolutePath());
p.command("C:\\Program Files (x86)\\...\\program.exe","Enqueue","%1",next.getAbsolutePath());
p.command("C:\\Program Files (x86)\\...\\program.exe","Enqueue","\"%1\"",next.getAbsolutePath());
p.command("C:\\Program Files (x86)\\...\\program.exe","/Enqueue","\"%1\"",next.getAbsolutePath());
"Not working" in this case meaning that the program is launched, but nothing happens (the file is not even opened).
If I switch them around in this order: (program, file, parameters) then the file is opened correctly, but the additional parameters do nothing, as if they weren't even there.
What is the correct way to translate those parameters into the ProcessBuilder command?
The first thing you need to do, is make "C:\Program Files (x86)\...\program.exe" /Enqueue "%1" into an array of [C:\Program Files (x86)\...\program.exe, /Enqueue, %1] otherwise ProcessBuilder will try and execute the whole String as a single command, which really isn't what you want.
Maybe something like...
String cmd = "\"C:\\Program Files (x86)\\...\\program.exe\" /Enqueue \"%1\"";
StringBuilder sb = new StringBuilder(cmd);
List<String> commands = new ArrayList<>(10);
while (sb.length() > 0) {
if (sb.charAt(0) == '"') {
int nextIndex = sb.indexOf("\"", 1);
if (nextIndex < 0) {
nextIndex = sb.length();
} else {
nextIndex++;
}
commands.add(sb.substring(1, nextIndex).replace("\"", ""));
sb.delete(0, nextIndex);
} else if (sb.charAt(0) == ' ') {
if (sb.length() > 1 && sb.charAt(1) != '"') {
int nextIndex = sb.indexOf(" ", 1);
if (nextIndex < 0) {
nextIndex = sb.length();
}
commands.add(sb.substring(1, nextIndex));
sb.delete(0, nextIndex);
} else {
sb.delete(0, 1);
}
}
}
System.out.println(commands);
Which will print...
[C:\Program Files (x86)\...\program.exe, /Enqueue, %1]
There's probably a really neat regular expression you could use to help with this, but this will get the job done, more or less.
Next, you want to replace %1 with the file you want to open. Now, you can do this within the previous code, which would be more efficient, but for demonstration purposes...
String[] parameters = {"Hello kitty"};
for (int index = 0; index < commands.size(); index++) {
String value = commands.get(index);
if (value.startsWith("%")) {
int parameter = Integer.parseInt(value.substring(1)) - 1;
if (parameter < parameters.length) {
commands.set(index, parameters[parameter]);
}
// You might want to think about what you want to do if you have
// more parameter marks then you do have actual parameter values
}
}
System.out.println(commands);
Which prints out...
[C:\Program Files (x86)\...\program.exe, /Enqueue, Hello kitty]
Which you can now pass to ProcessBuilder, for example...
ProcessBuilder pb = new ProcessBuilder(commands);
Now, you could do the String substitution at many different points in the code, in many different ways, this is just an example of one

Java opening images for sprites

I am making a game that needs multiple sets of sprites and they need to be stored in a form of 2d list/array. I have 2 objects that need sprites, you (which is the guy) and bee. I have the images sorted by these 2 characters, then their actions, then direction by the use of folders.
I made this code to open the "you" folder and insert the subfolder contents into a 2d arraylist that has moves down the side:
public void loadPic(){//open up all of the images and store them in an ArrayList
File folder = new File("img/youImgs/run/right");
File[] listOfFiles = folder.listFiles();
ArrayList<BufferedImage> runImgs=new ArrayList<BufferedImage>();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".png")) {
try {
runImgs.add(ImageIO.read(new File("img/youImg/run/right"+file.getName())));
}
catch (IOException e) {
}
}
}
youImgs.add(runImgs);
}
I do not know how to modify it to make it useful and work.
I need them to save into separate lists so I can run them.
If you have a better idea on how to add sprites, please let me know.
Please help me out.
thank you in advance.
I found out how to do this.
I edited my folder directory to have each move in a folder and then all of these folders in one youImg folder.
My code is below for anyone else that needs help.
public void loadPic(){//open up all of the images and store them in an ArrayList
String youDirectory="img/youImgs/";
File folder = new File(youDirectory);
File[] listOfFiles = folder.listFiles();
for(int i=0;i<listOfFiles.length;i++){
youImgs.add(new ArrayList<BufferedImage>());
}
for(int h=0;h<listOfFiles.length;h++){
File file=listOfFiles[h];
if(file.isDirectory()){
try{
youMoves.add(file.getName());
File folder2=new File(youDirectory+file.getName()+"/");
File[]listOfFiles2=folder2.listFiles();
for (int i = 0; i < listOfFiles2.length; i++){
File file2 = listOfFiles2[i];
if (file2.isFile() && file2.getName().endsWith(".png")){
youImgs.get(h).add(ImageIO.read(new File(youDirectory+file.getName()+"/"+file2.getName())));
}
}
}
catch(IOException e){}
}
}
}
Thank you to many of the other questions on this site to help me find the answer.

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);
}

JAVA - Array Out of Bounds Error

I have an issue with my logic and I would appreciate some pointers. My code produces the Array Out Of Bounds Exception when I try to iterate through an array of files in a directory and store the files that end in .txt within another array.
I think my issue is that the array of all files is larger than the array of txt files, that seems the most logical reason for the error. The problem is I don't know why its finding more occurrences of txt files in the second loop vs the first.
Here is the code:
public static void ListFiles(String file_dir) {
String files;
int txtCounter = 0;
File folder = new File(file_dir);
File[] listOfFiles = folder.listFiles();
//Count all txt files
for (int y = 0; y < listOfFiles.length; y++) {
if (listOfFiles[y].isFile()) {
files = listOfFiles[y].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
txtCounter++;//Add to the count
}
}
}
//Create array for the list of txt files.
String txtFiles[] = new String[txtCounter];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
//Add all txt files to new array txtFiles
txtFiles[i] = folder + files;
System.out.println(txtFiles[i]);
}
}
}
//Send array back to Main
//return txtFiles[];
}
Am I making this harder than it has to be? I'm trying to take a list of text files, replace certain words in the files, and combine them all into one file when complete.
Thanks!
UPDATED:
public static String[] ListManualSections(String file_dir) {
file_dir = file_dir + "\\manualSections\\";
String files;
//Create list of all files in the manualSections directory.
File folder = new File(file_dir);
File[] listOfFiles = folder.listFiles();
//Dynamic list of text files
ArrayList al = new ArrayList();
//Add each occurrence of a text file to the ArrayList
for (int i = 0; i < listOfFiles.length; i++) {
files = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && files.toLowerCase().endsWith(".txt")) {
al.add(folder + "\\" + files);
//System.out.println(al);
}
}
//Send list back to Main
String[] txtFiles = (String[]) al.toArray(new String[al.size()]);
return txtFiles;
}
This second for loop seems confused about whether it's iterating over txtFiles or over listOfFiles, which could have different lengths. In particular, you should probably not be writing to txtFiles[i] when i could be larger than the length of txtFiles.
Mostly, though, this code would be simpler if you just used an ArrayList.
As addition to the answer of #Louis, you could go with a separate counter for the file and txt-file. Like this:
int txtidx = 0;
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
//Add all txt files to new array txtFiles
txtFiles[txtidx] = folder + files;
System.out.println(txtFiles[txtidx]);
txtidx++;
}
}
}
instead of complicating matters, you can do this
Use Apache Commons io to list all your files
Collection<File> files = FileUtils.listFiles(new File("file_dir"), new String[]{"txt"}, true);
//use true if you want it to be recursive, i.e. to search subdirectories of file_dir
for (File file : files)
{
//you can then play with your file object here
}
Let me know if you have issues.
You're making this harder than it has to be.
You're passing over an array once to count how many text files there are and then, a second time, to add text files to another array.
Any implementer of the List<E> interface would be more appropriate than an array; you can then add elements on the fly. If you must have an array afterwards. you can always use the toArray method at the end.
Well look at this scenario -
listOfFiles is size 6, first loop you find 5 txt files, and the last element in listOfFiles is a txt file.
Then at the last iteration of second loop, you are trying to do txtFiles[5] = folder+files. That will throw the error because txtFiles is only 0-4.
Like Louis said, use ArrayList.
You could simply use File.listFiles(FileNameFilter) to get the files matching your criteria.
private File[] getTextFiles(String dir)
{
File folder = new File(dir);
return folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
}
Your second for loop iterates over all of the files, meaning that i = 0 .. N where N is the number of total files. But your text files could occur at any i here. The so even if there are only 2 text files, if they are found on the 6th iteration of the N total files, that is not the index you want to be using for your text file array.
I would suggest you create a counter for the index of the text file array and increment it as you add, or use a List.
String txtFiles[] = new String[txtCounter];
int txtIndex = 0;
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
//Add all txt files to new array txtFiles
txtFiles[txtIndex] = folder + files;
txtIndex++;
System.out.println(txtFiles[i]);
}
}
}

Categories