I have developed a desktop based searching project in java. I have recursively called the search function for searching operation.
My project is working well but it is unable to search in names of audio and video files.
I am putting my code of searching
public void searchFiles(String mainPath, String searchText){
mainFile = new File(mainPath);
System.out.append(mainFile.getAbsolutePath());
File[] roots = mainFile.listFiles();
Arrays.sort(roots);
for (int i = 0; i < roots.length; i++) {
try {
System.out.println(roots[i]);
SearchProgram searchProgram = new SearchProgram(roots[i], searchText);
} catch (Exception exception) {
}
}
}
-----------------------------------------------------------------------------------
class SearchProgram extends Thread {
File fileDir;
String fileName;
public SearchProgram(File d, String n) {
fileDir = d;
fileName = n;
this.start();
}
// this is a recursive file search function
#Override
public void run() {
if (check) {
try {
search(fileDir, fileName);
} catch (Exception exception) {
}
}
}
private void search(File dir, String name) {
if (check) {
String dirPath = dir.getAbsolutePath();
if (dirPath.length() > 60) {
lblCurrentLocation.setText("\\\\.............." + dirPath.substring(60, dirPath.length()));
} else {
lblCurrentLocation.setText(dirPath);
}
if (dir.getName().toLowerCase().endsWith(name.toLowerCase())) {
tableModel.addRow(new Object[]{dir.getAbsolutePath()});
} else if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
search(new File(dir, children[i]), name);
}
}
}
}
}
please suggest what is the problem with this code
Related
I'm working on a FileSystem implementation, and I'm having trouble with my Binary Search Tree locate method. Right now the way I have it structured. It will add additional files or something else that I'm unable to figure out.
As an example, I have the tree:
/
/ \
a b
/ / \
c h q
/
x
If the user inputs locate h, my program will output /acxh.
When the user inputs locate h, the output SHOULD be /bh
Here is my FileSystem class:
import java.io.IOException;
import java.util.ArrayList;
public class FileSystem {
private Directory root;
private Directory wDir;
private ArrayList<File> files = new ArrayList<File>();
// Constructor
public FileSystem() {
}
// Constructor with parameters
public FileSystem(Directory root) {
this.root = root;
wDir = root;
files.add(root);
}
// Returns the FileSystem's files
public ArrayList<File> getFiles() {
return files;
}
// Returns the working directory
public Directory getWDir() {
return wDir;
}
// Sets the working directory
public void setWDir(Directory d) {
wDir = d;
}
// Returns the root file. This will always be / in our program
public File getRoot() {
return root;
}
public File getFile(File f, String name) {
if (f.isDirectory()) {
for (File c : ((Directory) f).getChildren()) {
if (c.getName().equals(name))
return c;
}
}
return null;
}
// Currently only used in cat method, getFile is better
File findFile(File f, String name) {
if (f.getName().equals(name))
return f;
File file = null;
if (f.isDirectory()) {
for (File c : ((Directory) f).getChildren()) {
file = findFile(c, name);
if (file != null)
break;
}
}
return file;
}
// Returns true if file is found
boolean isFile(String name) {
File file = null;
file = getFile(wDir, name);
if (file != null) {
return true;
}
return false;
}
// Creates Directory
public void mkdir(String path) {
files.add(new Directory(path));
int size = files.size();
// Sets the parent
files.get(size - 1).setParent(wDir);
// Sets the child
wDir.addChild(files.get(size - 1));
}
// Changes working directory
public void cd(String s) {
if (s.equals("..")) {
if (wDir != root) {
wDir = wDir.getParent();
}
} else if (s.equals("/")) {
wDir = root;
} else {
wDir = (Directory) getFile(wDir, s);
}
}
// Provides absolute filename
public void pwd() {
if (wDir == root) {
System.out.println("/");
} else {
System.out.println(wDir.getPath());
}
}
// Lists children of current working directory
public void ls() {
ArrayList<File> children = wDir.getChildren();
if (children != null) {
for (int i = 0; i < children.size(); i++) {
String childName = children.get(i).getName();
System.out.print(childName + " ");
}
}
}
// Lists children of file(s) inputted by user
public void ls(File f) {
if (f instanceof TextFile) {
System.out.println(f.getPath());
} else {
ArrayList<File> children = ((Directory) f).getChildren();
if (children != null) {
for (int i = 0; i < children.size(); i++) {
String childName = children.get(i).getName();
System.out.print(childName + " ");
}
}
}
}
public void recLS(File f, String location) {
System.out.println(location + ":");
ls(f);
System.out.println("");
if (f.isDirectory()) {
ArrayList<File> children = ((Directory) f).getChildren();
for (File c : children) {
location += "/" + c.getName();
}
for (File c : children) {
recLS(c, location);
}
}
}
// Creates a TextFile or edit's TextFile's content if already exists in the
// tree
public void edit(String name, String content) {
files.add(new TextFile(name, content));
// Setting TextFile parent
files.get(files.size() - 1).setParent(wDir);
// Setting Parent's child
wDir.addChild(files.get(files.size() - 1));
}
// Prints the content of TextFile
public void cat(String name) {
File f = findFile(root, name);
System.out.println(((TextFile) f).getContent());
}
public void updatedb(Indexer i) throws IOException {
i.index(files);
}
public String locate(String s, Indexer i) {
return i.locate(s);
}
}
Here is my Indexer class:
import java.io.*;
import java.util.*;
class Entry implements Comparable<Entry> {
String word;
ArrayList<Integer> page = new ArrayList<Integer>();
Entry(String word) {
this.word = word;
}
public int compareTo(Entry e) {
return word.compareTo(e.word);
}
}
class Indexer {
private BinarySearchTree<Entry> bst;
public void index(ArrayList<File> files) throws IOException {
bst = new BinarySearchTree<Entry>();
int fileCount = 1;
for (int i = 0; i < files.size(); i++) {
String name = files.get(i).getName();
indexName(name, fileCount++);
}
}
private void indexName(String name, int fileCount) {
Entry e = new Entry(name);
Entry r = bst.find(e);
if (r != null) {
r.page.add(fileCount);
} else {
e.page.add(fileCount);
bst.add(e);
}
}
public String locate(String s) {
Entry e = new Entry(s);
ArrayList<String> path = new ArrayList<String>();
bst.locateHelper(e, bst.root, path);
String word = "";
for (int i = 0; i < path.size(); i++) {
word += path.get(i);
}
return word;
}
}
Here is my BinarySearchTree class:
import java.util.ArrayList;
public class BinarySearchTree<E extends Comparable> extends BinaryTree<E> {
private boolean addReturn;
private E deletedItem;
boolean add(E item) {
root = add(root, item);
return addReturn;
}
private Node<E> add(Node<E> n, E item) {
if (n == null) {
addReturn = true;
return new Node<E>(item);
} else if (item.compareTo(n.data) == 0) {
addReturn = false;
return n;
} else if (item.compareTo(n.data) < 0) {
n.leftChild = add(n.leftChild, item);
return n;
} else {
n.rightChild = add(n.rightChild, item);
return n;
}
}
public E find(E target) {
return find(target, root);
}
private E find(E target, Node<E> node) {
if (node == null) {
return null;
}
int result = target.compareTo(node.data);
if (result == 0) {
return node.data;
}
if (result < 0) {
return find(target, node.leftChild);
}
return find(target, node.rightChild);
}
public String locateHelper(Entry e, Node<Entry> node, ArrayList<String> path) {
if (node == null) {
return null;
}
int result = e.compareTo(node.data);
if (result == 0) {
path.add(node.data.word);
return node.data.word;
}
if (result < 0) {
path.add(node.data.word);
return locateHelper(e, node.leftChild, path);
}
path.add(node.data.word);
return locateHelper(e, node.rightChild, path);
}
}
I apologize for having a lot of code in the post, I know I'm supposed to keep it minimal, but I'm sure you will need to look at these 3 classes at least to provide some help. If anything else is needed just let me know and I'll edit this post to provide it.
i want to populate Folder Name With Sub Folder name on KendoDrop Down . so i want to Convert Folder Directory in JSOn Format How can i Do That ?
public class FolderPath {
public static void main(String[] args) throws IOException {
File currentDir = new File("Folder URL "); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
sb1 = sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
String str = file.getCanonicalPath();
displayDirectoryContents(file);
} else {
}
}
sb1.deleteCharAt(sb1.length() - 1);
sb1 = sb1.append("]");
System.out.println("s2==>" + sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here i am Not Getting Full Directroy into JSOn Please Help
You are creating a StringBuilder object on each iteration. That's why your concatenation does not work.
Consider the contents of you C:\test is composed of 3 directories:
c:\test
|
+--css
| +--less
+--js
The code below, returns:
[{"JSONKEY":"C:\test\css"},
{"JSONKEY":"C:\test\css\less"},
{"JSONKEY":"C:\test\js"}]
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class FolderPath {
private static FileFilter onlyDirectories = new FileFilter() {
#Override
public boolean accept(File file) {
return file.isDirectory();
}
};
public static void main(String[] args) {
File currentDir = new File("C:\\test"); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
doDisplayDirectoryContents(dir, sb1);
if (sb1.length() > 1) {
sb1.deleteCharAt(sb1.length() - 1);
}
sb1.append("]");
System.out.println(sb1);
}
private static void doDisplayDirectoryContents(File dir, StringBuilder sb1) {
File[] files = dir.listFiles(onlyDirectories);
if (files != null) {
for (File file : files) {
try {
sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
doDisplayDirectoryContents(file, sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public List<Object> getDirectoryContents(String path) throws IOException {
File directory = new File(path);
File[] files;
enter code here FileFilter fileFilter = file -> file.isDirectory() || file.isFile();
files = directory.listFiles(fileFilter);
List<Object> directoryContent = new ArrayList<>();
if(files != null) {
for (int i = 0; i < files.length; i++) {
File filename = files[i];
String folderPath[] =filename.toString().split("/");
if(files[i].isDirectory()) {
Folder folder = new Folder();
folder.setName(folderPath[folderPath.length - 1]);
folder.setType("folder");
folder.setChildren(mapper.readTree(mapper.writeValueAsString(getDirectoryContents(path + "/" + folder.getName()))));
directoryContent.add(folder);
}
else{
Files file = new Files();
file.setName(folderPath[folderPath.length - 1]);
file.setType("file");
directoryContent.add(file);
}
}
}
return directoryContent;
}
public class Files {
private String name;
private String type = "file";
}
public class Folder {
private String name;
private String type = "folder";
private JsonNode children;
}
For example, I am getting the error here- this is just a snippet. I got the error 3 times in 3 different operators.
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
I also have the same error here:
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
And then in my second class (the user interface portion), I keep getting this error: Exception in thread "main" java.lang.NoClassDefFoundError: Directory
Here is the entire code for that class:
import java.io.*;
import java.util.*;
public class DirectoryWithObjectDesign {
public static void main(String[] args) throws IOException {
String directoryDataFile = "Directory.txt";
Directory d = new Directory(directoryDataFile);
Scanner stdin = new Scanner(System.in);
System.out.println("Directory Server is Ready!");
System.out.println("Format: command name");
System.out.println("Enter ^Z to end");
while (stdin.hasNext()) {
String command = stdin.next();
String name = stdin.next();
if (command.equalsIgnoreCase("find")) {
if (d.inDirectory(name))
System.out.println(name + " is in the directory");
else
System.out.println(name + " is NOT in the directory");
}
else if (command.equalsIgnoreCase("add")) {
if (d.add(name))
System.out.println(name + " added");
else
System.out.println(name + " cannot add! " + "no more space or already in directory");
}
else if (command.equalsIgnoreCase("delete")) {
if (d.delete(name))
System.out.println(name + " deleted");
else
System.out.println(name + " NOT in directory");
}
else {
System.out.println("bad command, try again");
}
}
}
}
And here is the code for my directory class:
import java.util.*;
import java.io.*;
public class Directory {
//public static void main(String[] args) {
final int maxDirectorySize = 1024;
String directory[] = new String[maxDirectorySize];
int directorySize = 0;
File directoryFile = null;
Scanner directoryDataIn = null;
public Directory(String directoryFileName) {
directoryFile = new File(directoryFileName);
try {
directoryDataIn = new Scanner(directoryFile);
}
catch (FileNotFoundException e) {
System.out.println("File is not found, exiting!" + directoryFileName);
System.exit(0);
}
while (directoryDataIn.hasNext()) {
directory[directorySize++] = directoryDataIn.nextLine();
}
}
public boolean inDirectory(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return true;
else
return false;
}
}
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
public void closeDirectory() {
directoryDataIn.close();
PrintStream directoryDataOut = null;
try {
directoryDataOut = new PrintStream(directoryFile);
}
catch (FileNotFoundException e) {
System.out.printf("File %s not found, exiting!", directoryFile);
System.exit(0);
}
String originalDirectory[] = {"Mike","Jim","Barry","Cristian","Vincent","Chengjun","susan","ng","serena"};
if (originalDirectory == directory)
System.exit(0);
else
for (int i = 0; i < directorySize; i++)
directoryDataOut.println(directory[i]);
directoryDataOut.close();
}
}
The point is that the compiler can't know if your for loop will be entered at all. Therefore you need a final return after the end of the for loop, too. In other words: any path that can possibly be taken within your method needs a final return statement. One easy way to achieve this ... is to have only one return statement; and put that on the last line of the method. This could look like:
Object getSomething() {
Object rv = null; // rv short for "returnValue"
for (int i=0; i < myArray.length; i++) {
if (whatever) {
rv = godKnowsWhat;
} else {
rv = IdontCare;
}
}
return rv;
}
In your second example, the indenting seems to indicate that you have a return in the else statement
directory[directorySize++] = name;
return true;
But when you look closer, you will realize that there are TWO statements after the else
else
directory[directorySize++] = name;
return true;
So this actually reads like
else
directory[directorySize++] = name;
return true;
Meaning: always put {braces} around all your blocks, even for (supposedly) one-liner then/else lines. That helps to avoid such mistakes, when a one-liner turns into a two-liner (or vice versa ;-)
The "NoClassDefFoundException" means: within the classpath that is specified to java ... there is no class Directory.class
To resolve that, you should study what the java classpath is about; and how to set it correctly.
I am building an app with a self-made LruDiskCache to reduce loading times. The LruDiskCache downloads a file if it is not already present and returns it via a callback. I'm having a very weird issue where the first image isn't loaded properly. This only happends the first time a activity is started. If you open the same activity a secon time the image is loaded properly.
After debugging i found that i get the following debug message: --- SkImageDecoder Factory returned null. I've read multiple issues regarding this problem, but the all involve downloading an image through an inputstream, while i'm first downloading the image to persistent storage.
My cache-class:
public class LruDiskCache {
private static final String LOGTAG = "LruDiskCache";
//Cache size
private final long cacheMaxSize;
private volatile long currentCacheSize;
public static final int DEFAULT_CACHE_SIZE_KB = 1024;
public static final int MINIMUM_CACHE_SIZE_KB = 128;
//Preferences
private final String cachePreferencesName;
private final String chachePreferencesSize = "cacheSize";
private final SharedPreferences cachePreferences;
//Lock
private final Object mDiskCacheLock = new Object();
//Cache Path
private final File cachePath;
//Initialisation
private boolean openingCache;
//Static variables
private static final long BYTES_IN_KB = 1024;
public LruDiskCache (Context c, String cacheName, int cacheMaxSizeKB){
//Preferences
cachePreferencesName = cacheName + "CachePreferences";
cachePreferences = c.getSharedPreferences(cachePreferencesName, Context.MODE_PRIVATE);
//Paths
cachePath = new File(c.getFilesDir().getPath()+"/"+cacheName);
//Cache size
if(cacheMaxSizeKB < MINIMUM_CACHE_SIZE_KB){
throw new IllegalArgumentException
("Invalid cache size, size must be bigger than "
+ MINIMUM_CACHE_SIZE_KB + "kb.");
}
cacheMaxSize = cacheMaxSizeKB * BYTES_IN_KB;
//Initialize
openingCache = true;
new InitializeCache().execute();
}
//PUBLIC METHODS
public synchronized void getRemoteFile(URL remoteFile, Callback c){
if(openingCache){
try {
mDiskCacheLock.wait(1000);
} catch (InterruptedException e) {
c.onRequestedFileRetrieved(null, false);
}
}
String path = createFilePath(remoteFile);
File f = new File(path);
if(f.exists() && f.isFile()){
f.setLastModified(System.currentTimeMillis());
c.onRequestedFileRetrieved(f, true);
} else {
new RemoteFileDownloadTask(remoteFile, f, c).execute();
}
}
//PRIVATE METHODS
private String createFilePath(URL key){
return cachePath + "/" + key.getHost() + key.getPath();
}
private synchronized void cleanUpCache(){
long cacheSize = getDirSize(cachePath);
int failedToDeleteCounter = 0;
while(cacheSize > cacheMaxSize){
File toDelete = getFirstRequestedFile(cachePath);
Log.w("LruDiskCache", "File to be deleted: " + toDelete.getName() + ".");
long toDeleteSize = toDelete.length();
if(!toDelete.delete()){
failedToDeleteCounter++;
} else {
Log.w("LruDiskCache", "Deleted file to clean cache.");
cacheSize -= toDeleteSize;
}
if(failedToDeleteCounter > 100){
Log.w("LruDiskCache", "Failed to clean cache, could not delete files.");
break;
}
}
}
private File getFirstRequestedFile(File directory){
File first = null;
for(File f : directory.listFiles()){
if(f.isFile()){
if(first == null){
first = f;
} else {
if(f.lastModified() < first.lastModified()){
first = f;
}
}
} else if (f.isDirectory()) {
File firstReqInDir = getFirstRequestedFile(f);
if(first == null){
first = firstReqInDir;
} else if (firstReqInDir.lastModified() < first.lastModified()){
first = firstReqInDir;
}
}
}
return first;
}
private long getDirSize(File dir) {
long bytes = 0;
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
bytes += getDirSize(f);
} else {
bytes += f.length();
}
}
return bytes;
}
//ASYNC TASKS
private class InitializeCache implements Runnable{
public void execute(){
new Thread(this).start();
}
#Override
public void run() {
synchronized (mDiskCacheLock) {
Log.d("Initialize cache", "Starting init...");
if (!cachePath.exists()) {
if (!cachePath.mkdirs()) {
mDiskCacheLock.notifyAll();
openingCache = false;
}
}
currentCacheSize = getDirSize(cachePath);
Log.d("LruDiskCache", "Cache size: " + currentCacheSize / BYTES_IN_KB + "kb.");
if(currentCacheSize > cacheMaxSize){
cleanUpCache();
}
Log.d("Initialize cache", "Did init...");
mDiskCacheLock.notifyAll();
openingCache = false;
}
}
}
private class RemoteFileDownloadTask extends AsyncTask<Void, Void, File> {
private final Callback c;
private URL remoteFile;
private File localFile;
protected RemoteFileDownloadTask(URL remoteFile, File localFile, Callback c){
this.c = c;
this.remoteFile = remoteFile;
this.localFile = localFile;
}
#Override
protected File doInBackground(Void... params) {
if(retrieveRemoteFile(remoteFile, localFile)){
return localFile;
} else {
return null;
}
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
currentCacheSize += file.length();
if(currentCacheSize > cacheMaxSize){
cleanUpCache();
}
c.onRequestedFileRetrieved(file, true);
}
public boolean retrieveRemoteFile(URL remote, File filePath) {
try {
if (filePath.exists() && filePath.isFile()) {
return true;
} else {
if (!filePath.getParentFile().exists()) {
if (!filePath.getParentFile().mkdirs()) {
return false;
}
}
}
} catch (Exception e){
return false;
}
Log.w("LruDiskCache", "Created empty file: " + filePath.getPath());
Log.w("LruDiskCache", "Downloading source from: " + remote.toString());
try {
FileOutputStream fos;
InputStream is;
BufferedInputStream bis;
fos = new FileOutputStream(filePath);
HttpURLConnection con = (HttpURLConnection) remote.openConnection();
if(con.getResponseCode() != HttpURLConnection.HTTP_OK){
Log.e("Receiver", "HTTP Response code is not OK");
return false;
}
is = con.getInputStream();
bis = new BufferedInputStream(is);
while(bis.available() > 0){
fos.write(bis.read());
}
bis.close();
is.close();
fos.close();
} catch (Exception e) {
return false;
}
Log.d("LruDiskCacheReceiver", filePath.getPath() + " received, " + filePath.length() + " bytes.");
return true;
}
}
//CALLBACK INTERFACE
public interface Callback{
public abstract void onRequestedFileRetrieved(File f, boolean success);
}
}
And the implementation is shown here:
URL emblemURL = new URL(data[position].getEmblemUrl());
cache.getRemoteFile(emblemURL, new LruDiskCache.Callback() {
#Override
public void onRequestedFileRetrieved(File f, boolean success) {
if (success && f.exists()) {
Drawable bitmap = Drawable.createFromPath(f.getAbsolutePath());
emblem.setImageDrawable(bitmap);
}
}
});
Any help is appreciated.
I have the following code to iterate over folders and files in the class path and determine the classes and get a field with a ID and print them out to a logger. This is working fine if I run this code in my IDE, but if I package my project into a JAR file and this JAR file into a EXE file with launch4j, I can't iterate over my classes again.
I get the following path if I try to iterate over my classes in the JAR/EXE file:
file:/C:/ENTWICKLUNG/java/workspaces/MyProject/MyProjectTest/MyProjectSNAPSHOT.exe!/com/abc/def
How can I achieve this to iterate over all my classes in my JAR/EXE file?
public class ClassInfoAction extends AbstractAction
{
/**
* Revision/ID of this class from SVN/CVS.
*/
public static String ID = "#(#) $Id ClassInfoAction.java 43506 2013-06-27 10:23:39Z $";
private ClassLoader classLoader = ClassLoader.getSystemClassLoader();
private ArrayList<String> classIds = new ArrayList<String>();
private ArrayList<String> classes = new ArrayList<String>();
private int countClasses = 0;
#Override
public void actionPerformed(ActionEvent e)
{
countClasses = 0;
classIds = new ArrayList<String>();
classes = new ArrayList<String>();
getAllIds();
Iterator<String> it = classIds.iterator();
while (it.hasNext())
{
countClasses++;
//here I print out the ID
}
}
private void getAllIds()
{
String tempName;
String tempAbsolutePath;
try
{
ArrayList<File> fileList = new ArrayList<File>();
Enumeration<URL> roots = ClassLoader.getSystemResources("com"); //it is a path like com/abc/def I won't do this path public
while (roots.hasMoreElements())
{
URL temp = roots.nextElement();
fileList.add(new File(temp.getPath()));
GlobalVariables.LOGGING_logger.info(temp.getPath());
}
for (int i = 0; i < fileList.size(); i++)
{
for (File file : fileList.get(i).listFiles())
{
LinkedList<File> newFileList = null;
if (file.isDirectory())
{
newFileList = (LinkedList<File>) FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
if (newFileList != null)
{
for (int j = 0; j < newFileList.size(); j++)
{
tempName = newFileList.get(j).getName();
tempAbsolutePath = newFileList.get(j).getAbsolutePath();
checkIDAndAdd(tempName, tempAbsolutePath);
}
}
}
else
{
tempName = file.getName();
tempAbsolutePath = file.getAbsolutePath();
checkIDAndAdd(tempName, tempAbsolutePath);
}
}
}
getIdsClasses();
}
catch (IOException e)
{
}
}
private void checkIDAndAdd(String name, String absolutePath)
{
if (name.endsWith(".class") && !name.matches(".*\\d.*") && !name.contains("$"))
{
String temp = absolutePath.replace("\\", ".");
temp = temp.substring(temp.lastIndexOf(/* Class prefix */)); //here I put in the class prefix
classes.add(FilenameUtils.removeExtension(temp));
}
}
private void getIdsClasses()
{
for (int i = 0; i < classes.size(); i++)
{
String className = classes.get(i);
Class<?> clazz = null;
try
{
clazz = Class.forName(className);
Field idField = clazz.getDeclaredField("ID");
idField.setAccessible(true);
classIds.add((String) idField.get(null));
}
catch (ClassNotFoundException e1)
{
}
catch (NoSuchFieldException e)
{
}
catch (SecurityException e)
{
}
catch (IllegalArgumentException e)
{
}
catch (IllegalAccessException e)
{
}
}
}
}
You cannot create File objects from arbitrary URLs and use the usual filesystem traversal methods. Now, I'm not sure if launch4j does make any difference, but as for iterating over the contents of plain JAR file, you can use the official API:
JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile file = connection.getJarFile();
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
JarEntry e = entries.nextElement();
if (e.getName().startsWith("com")) {
// ...
}
}
Above snippet lists all the entries in the JAR file referenced by url, i.e. files and directories.