Java - Unable to Detect Files - java

Following on from my previous question, my program doesn't detect the 300 images that have just been created in a particular directory; instead, it only detects desktop.ini, which is not the case as I can physically see that the files have been created within said directory and do exist.
Can somebody please explain why this happens as when I run the program the next time, it seems to work just fine?
The only way that something is detected within the directory on the first run is when there is at least one file which exists in the directory before the program is compiled and executed.
Many thanks.
UPDATE: Files are detected as follows:
//Default greyscale image directory (to convert from greyscale to binary).
static File dirGrey = new File("test_images\\Greyscale");
//Array of greyscale image filenames.
static File imgListGrey[] = dirGrey.listFiles();

without knowing how you create the images, this question is akin to 'How many kittens are under my desk right now?'
Are you creating the files yourself? If so, are you closing any file handles referring to those files once they are created?

You're creating the file list in a static array, and it's created when the class containing the array is loaded by the Java class loader, which is probably before you create the image files. That's why the array contains an outdated list.
static is rarely needed, mostly useful for constants (things that never change, such as 42), for pure functions (Math.sqrt()) and a few other special cases. When you use it, you have to learn all the tricky initialization order stuff. Otherwise, just stick with non-static variables.

Related

Displaying an image from a href

image.jpg
There is a load of lines like this with different pictures.
What i need to do is to make a script of some sort that would allow displaying those images without the need to write anything new in the body (it has to find the files from href's and display them ... without causing any more work for a person who puts those pictures there) and without the need to reorganize files (those files are tied to many other things ... change in the directory = everything crashes)
but i cant just find much ... most of the scripts i find requires me to place files in a specific folder or even worse ... to make img src tags for them
Can anyone point me towards some solution here ?
I'm not exactly clear on the question, but if I decipher it correctly a possible solution is to user scandir to read the contents of a directory. Likely will need to modify inside the foreach loop to fit your design (not sure if you have embedded script or not) but this will dynamically fetch and display images inside a directory.
if ($images = scandir('path_to_your_image_directory')) {
foreach ($images as $image) {
print '$image.jpg'; // Might need to preface the $image variable with path to your image directory
}
}

Make file array print deafult names in Java?

My problem is when I print the files within the directory, it prints out stuff like 'thumbs.db' and 'desktop.ini'. How to i make it print the name itself. All the files are .png by the way
static File overlayPath1 = new File(Minecraft.getMinecraft().mcDataDir, "\\TVMod\\" + filesList[0].getName());
thumbs.db and desktop.ini are both files in this directory, but normally in Windows they're hidden. However, because they're still there, they'll show up in your fileList.
If you don't want to use these files, you're going to have to skip them somehow. The implementation I'd suggest is to convert it to an ArrayList, then remove elements that don't match the .png extension.
However, without knowing more about your implementation, though, I can't easily suggest a way to do this.

Java find where a class is used in the code - programmatically

I have a List of classes which I can iterate through. Using Java is there a way of finding out where these classes are used so that I can write it out to a report?
I know that I can find out using 'References' in Eclipse but there are too many to be able to do this manually. So I need to be able to do this programmatically. Can anyone give me any pointers please?
Edit:
This is static analysis and part of creating a bigger traceability report for non-technical people. I have comprehensive Javadocs but they are not 'friendly' and also work in the opposite direction to how I need the report. Javadocs start from package and work downwards, whereas I need to start a variable level and work upwards. If that makes any sense.
You could try to add a stacktrace dump somewhere in the class that isolates the specific case you are looking for.
public void someMethodInMyClass()
{
if (conditions_are_met_to_identify)
{
Thread.dumpStack();
}
// ... original code here
}
You may have to scan all the sources, and check the import statements. (Taking care of the * imports.. having to setup your scanner for both the fully Qualified class name and its packagename.*)
EDIT: It would be great to use the eclipse search engine for this. Perhaps here is the answer
Still another approach (probably not complete):
Search Google for 'java recursively list directories and files' and get source code that will recursively list all the *.java file path/names in a project.
For each file in the list:
1: See if the file path/name is in the list of fully qualified file names you are interested in. If so, record is path/name as a match.
2: Regardless if its a match or not, open the file and copy its content to a List collection. Iterate through the content list and see if the class name is present. If found, determine its path by seeing if its in the same package as the current file you are examining. If so, you have a match. If not, you need to extract the paths from the *.import statements, add it to the class name, and see if it exists in your recursive list of file path/names. If still not found, add it to a 'not found' list (including what line number it was found on) so you can manually see why it was not identified.
3: Add all matches to a 'found match' list. Examine the list to ensure it looks correct.
Not sure what you are trying to do, but in case you want to analyse code during runtime, I would use an out-of-the box profiler that shows you what is loaded and what allocated.
#Open source profilers: Open Source Java Profilers
On the other hand, if you want to do this yourself (During runtime) you can write your own custom profiler:
How to write a profiler?
You might also find this one useful (Although not exactly what you want):
How can I list all classes loaded in a specific class loader
http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html
If what you are looking is just to examine your code base, there are really good tools out there as well.
#see http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis

How to avoid hardcoding file-references?

My Code:
I'm currently developing a game and throughout several different parts of the code I'm using some resources (Images/Sounds/Animations etc.). To avoid loading the same resource twice I wrote a ResourceManager, that returns the wanted resource if I pass a string to it.
Here's an example:
Image myImage = imageManager.getImage("princess");
This way I can reference a resource without knowing the name of the file or position of it, when I want to use it.
The trick here is that I have to load the images before I can get them like so:
imageManager.loadImage("res/princessImage.png", "princess");
This creates the ImageObject from the given file, and stores it into a HashMap with the given key.
My Problem:
I really don't want to hardcode the paths to these resources, because I'd have to change the sourcecode every time I decide to move or rename any of the resource-files.
A possible solution (?):
I thought about creating another HashMap that reads some kind of configFile and maps the in-code-resource-names to the resource-paths in a HashMap. The file would look somewhat like this:
princess: res/princess.png
hero: res/hero.png
sword: res/items/sword.png
This way I could use resource-names like "princess", "hero" or "sword" safely and don't worry about their position on the hard drive while I'm coding. Whenever I move or rename a resource-file I just update the path/name in this configFile and everything would be fine.
On the other hand I think it's pretty ugly to have one giant file that maps every in-code-resource-name to a path. This could result in one giant String to String HashMap which I'd have to store in the ResourceManager aswell. Things could get pretty confusing/unclear.
Does anyone have a better solution for me?
I'd really appreciate your help,
Thanks :)
Using a config or resource file as you described is a fine approach. Instead of populating a HashMap, though, consider using ResourceBundle or PropertyResourceBundle. It is designed to hold/access such things. http://docs.oracle.com/javase/6/docs/api/java/util/ResourceBundle.html

Why doesn't File.renameTo(...) create sub-directories of destination?

Why doesn't File.renameTo(...) create sub-directories contained in the destination file path?
For instance,
File source = new File(System.getProperty("user.dir") +
"/src/MyFolder/MyZipFolder.zip");
File dest = new File(System.getProperty("user.dir") +
"/src/MyOtherFolder/MyZipFolder.zip");
System.out.println(source.renameTo(dest));
Since MyOtherFolder does not exist, this will always return false. In order for this to work, I have to ensure that all sub-directories exist either by creating them programmatically(i.e. mkdirs()), or manually. Is there a reason why this functionality was not included in this method?
Why?
Possibly for consistency / compatibility with the APIs that typical operating systems and other programming language runtime libraries provide.
Possibly because it would be a bad idea to create the intermediate directories if the user didn't really mean this to happen; e.g. if he / she simply mistyped one of the directory names in the path.
But it is not really relevant. The bottom line is that this is the way that the renameTo method behaves.
The current File API isn't very well implemented in Java. There is a lot of functionality that would be desirable in a File API that isn't currently present such as move, copy and retrieving file metadata.
I don't think anyone will be able to give you an answer as to why the API is written as is. Probably a poor first draft that went live and couldn't be changed due to backwards compatibility issues.
These issue have been addressed in the upcoming Java 7. A entirely new API has been created to deal with files java.nio.file.Files.
Creating sub-directories may be considered as unexpected side effect from other point of view. Are you sure everyone needs it implicitly?
You have answers but I was thinking along the lines:
A feature request to add a new method File.renameTo(File src, File destination, int makeDirs)
with three constants for makeDirs:
1) do not make sub folder(s)/ dirs
2) only make the final folder if it does not exist meaning if you specify /r1/r2/r3/file.extn then only make r3 if it does not exist, if r2 or any other does not exist then return false.
3) make all possible sub dirs
if its a OS that does not have sub folders then do as you do now
the old method would remain as is

Categories

Resources