I am currently working on a project for school, it is Java based and I am using Eclipse on Linux Mint to write it. The assignment says use the statement String[] filenames = new java.io.File("icons).list(); to create an array of file names.
The problem is I am not sure what to do with this, I have spent the past few hours searching the Internet and my textbook, but to no avail. Does it need to be a separate method?
Below is my guess for the needed code in the model (the project is to make a matching game, with a GUI) the names will have to be converted later on into actual icons, but I am pretty sure I have that part figured out, I just can't seem to get the darn files into the array!!
Thanks in advance,
public String[] list() {
String[] fileNames = new java.io.File("icons").list();
return fileNames;
}
In Java, the File class does not necessary represent an "existing" file on the file system. For example:
File f = new File("some_unknown_unexisting_file.bob");
System.out.println(f.exists()); // most likely will print 'false'
Also, the class resolves the file from the current working directory. You may get this directory with
System.out.println(new File(".").getAbsolutePath());
In your case, if you can, I would suggest getting a File[] array with :
File[] files = new File("icons").listFiles(new FileFilter() {
#Override
public boolean accept(File f) {
return !f.isDirectory() && f.canRead();
}
});
for (File f : files) {
System.out.println(f.getAbsolutePath());
}
which will return an array of File objects which are not folders and that you can open for reading (note that this is not always true, but is just fine in your case).
But if you have to use list(), then this is equivalent :
File parent = new File("icons");
String[] fileStr = parent.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
File f = new File(dir, name);
return !f.isDirectory() && f.canRead();
}
});
for (String f : fileStr) {
System.out.println(new File(parent, f).getAbsolutePath());
}
Also, with your list of files (String[]), you can create an icon using :
String filename = fileStr[i]; // some file name within the array
ImageIcon icon = new ImageIcon("icons" + File.separator + filename);
or with your list of files (File[]), it is cleaner :
File file = files[i]; // some file within the File[] array
ImageIcon icon = new ImageIcon(file.getAbsolutePath());
Good luck.
The code you wrote looks okay. Are you sure the folder "icons" exists where Java is looking?
Try this:
File f = new File("icons");
System.out.println("Does icons exist?" + f.exists());
System.out.println("Is it a dir?" + f.isDirectory());
System.out.println("How many files does it contain?" + f.list().length);
Good luck!
I've had the same problem. When I tried moving the icons folder into the folder just before the src folder, it seems to work. Not sure what I will do when I submit the assignment, as for it to work in JCreator, I believe it has to be with the .java files.
Related
I'm a newcomer to mobile programming and want to start off with a little Musicplayer-App. I need to search for all files which end with .mp3, .m4a, .wav, and so on. To do this, I want to first get a list of all files and then filter out the audio-files.
However, when I use getExternalStorageDirectory to get the path to the storage it returns "/storage/3139-6333", which is obviously not correct.
Basically I'm just curious why I get this result and how to fix it.
It's to be assumed that READ_EXTERNAL_STORAGE is permitted.
Thanks in advance.
String state = Environment.getExternalStorageState();
if ((Environment.MEDIA_MOUNTED.equals(state)||Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)))
{
File sd_card = Environment.getExternalStorageDirectory(); //"/storage/3139-6333"
File[] listFile = sd_card .listFiles(); //null
}
I guess you already have the path where you wish to do file search, if yes then you can use basic dfs algorithm to search your desired file.
below is example code for that, you can put any format in end to check all files for it.
public void search(String path){
File file = new File(path);
File[] files = file.listFiles();
if (files!=null) {
for (File f : files) {
if (f.isDirectory()) {
this.search(f.getAbsolutePath());
}
if (f.getAbsolutePath().endsWith(".txt")) {
System.out.println(f.getAbsolutePath());
}
}
}
}
hope this will help.
I am trying to create a method that searches inside a folder for .png files and returns a String array with the respective path to each file. It must look inside a resource folder placed NOT in the src, but in project.
The following code works when running from within Eclipse:
// Analyzes specified folder and returns a file array
// populated with the .png files found in that folder
private File[] imageReader(String filePath) {
File folder = new File(filePath);
return folder.listFiles (new FilenameFilter() {
public boolean accept(File filePath, String filename)
{ return filename.endsWith(".png"); }
});
}
// Converts the file array into a string array
private String[] listPngFiles(String filePath) {
File[] imagesFileArray = imageReader(filePath); // file array
String[] imagesStringArray = new String[imagesFileArray.length];
for(int i=0; i<imagesFileArray.length; i++) {
imagesStringArray[i] = "" + imagesFileArray[i];
imagesStringArray[i] = imagesStringArray[i].substring(6); // discards "/images" from directory string
}
return imagesStringArray;
}
However it is not working when I run the exported executable JAR file. This is my current project setup:
.
I have tried the following code but it did not work either:
ClassLoader classLoader = getClass().getClassLoader();
File folder = new File(classLoader.getResource(filePath).getFile());
The reason I am doing this is because I want to have a JButton display an icon chosen from one of the sub folders inside the images resource folder. My JButton already has the following code:
.setIcon(new ImageIcon(GameLogic.class.getResource(**insert listPngFiles array element here**)));
Your help on the matter would be greatly appreciated.
You can achieve this by using Reflections, take a look at getResources
I have a Java program that I am using to scan a directory to look for certain files. It finds the files but now I am trying to get the code to open the files once it finds them, but I am not sure how to do that.
Here a part of my code
File file = new File("/Users/******/Desktop/******");
String[] A = file.list();
File[] C = file.listFiles();
for (String string : A) {
if (string.endsWith(".txt")) {
System.out.println(string);
}
if (string.contains("******")) {
System.out.println("It contains X file");
}
}
I am trying to get it so once it finds the files ending in .txt, it opens all of them
I have tried using Google on how to solve his, I came across .getRuntime() and so I tried
try{
Runtime.getRuntime().exec("******.txt");
} catch(IOException e){
}
But I am not fully understanding how how this works. I am trying to get to so that once it finds the files it opens them. I am not trying to have the IDE open the text on the screen. I want the actual Notepad/TextEdit program to open.
File[] files = new File("/Users/******/Desktop/******").listFiles();
for (File f : files) {
String fileName = f.getName();
if (fileName.endsWith(".txt")) {
System.out.println(fileName);
}
if (fileName.contains("******")) {
System.out.println("It contains X file");
}
}
So far I have a list of images and I want to rename them based on information I get from a database.
List of images:
IBImages = ["foo1", "foo2", "foo3"]
private static void buildTheme(ArrayList<String> IBImages) {
String bundlesPath = "/a/long/path/with/dest/here";
for (int image = 0; image < IBImages.size(); image++) {
String folder = bundlesPath + "/" + image;
File destFolder = new File(folder);
// Create a new folder with the image name if it doesn't already exist
if (!destFolder.exists()) {
destFolder.mkdirs();
// Copy image here and rename based on a list returned from a database.
}
}
}
The JSON you get from the database might look something like this. I want to rename the one image that I have to all of the names in the list of icon_names
{
"icon_name": [
"Icon-40.png",
"Icon-40#2x.png",
"Icon-40#3x.png",
"Icon-Small.png",
"Icon-Small#2x.png",
]
}
You can't have into directory few files with same name at once. You need to either copy your file once and rename it, or create empty file with new name and copy bits from original file into it. Second approach is quite easy with Files class and its copy(source, target, copyOptions...) method.
Here is simple example of copying one file located in images/source/image.jpg to new files in image/target directory while giving them new names.
String[] newNames = { "foo.jpg", "bar.jpg", "baz.jpg" };
Path source = Paths.get("images/source/image.jpg"); //original file
Path targetDir = Paths.get("images/target");
Files.createDirectories(targetDir);//in case target directory didn't exist
for (String name : newNames) {
Path target = targetDir.resolve(name);// create new path ending with `name` content
System.out.println("copying into " + target);
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
// I decided to replace already existing files with same name
}
Ok so part of my program searches the C drive for all mp3 files, the only problem is that it won't go into and subfolders. Here is my code so far.
public static List<String> ListFiles() {
List<String> files = new ArrayList<String>();
File folder = new File("C:/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile() && file.toString().contains(".mp3")) {
String fileS = file.getName();
files.add(fileS);
}
}
return files;
}
Try a recursive approach. The path is the current directory that you're in. Recursively call this on each folder and you will get to each file.
public void walk(String path) {
File root = new File(path);
File[] list = root.listFiles();
if (list == null) return;
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath());
}
else {
//do what you want with files
}
}
}
Test whether file is a folder. If it is, pass it to ListFiles and append the return value to files.
For this to work, you need to change ListFiles to accept a File object as argument and start your search with this File instead of with "C:/"
Look into DirectoryStream<Path> class and the Files.isDirectory() method. Basically what you want to do is to check whether each Path is a file or directory.
If it is a directory, you call your method again. Else, you continue iterating.
Globbing is also possible with a directory stream. Saves you a lot of time instead of having to manually check file extensions.
If you wish to continue with your method or with directory stream, you will need to make a few modifications to your program to accomodate recursion.
If you want to do this yourself, you need to make it recursive. Which is what Oswald is getting at. A recursive method is a method that calls itself. So when you search a folder, for each element in it, if its an mp3, add it to the list, if its a folder, call your method again passing that folder in as the input.
I know it's Java question but why not just use Groovy and do it like:
static List<String> listMp3s() {
List<String> files = []
File rootFolder = new File('C:/')
rootFolder.eachFileRecurse(FileType.FILES) {
if (it.name.endsWith('.mp3')) {
files << it.name
}
}
return files
}